如何以正确的 json 格式动态创建 JSON,并不断将新数据附加到同一对象



我有一个表单,用户在其中输入电子邮件和密码,并且在提交时,JSON是动态创建的。当我再次使用其他用户详细信息登录时,相同的 JSON 会更新,但使用新对象,因此我的 JSON 会损坏。下面是用于创建 JSON 的 JS 函数 -'var g_objJSON = {};

    /** setJSON - Create JSON object
    * Returns - Nothing
    **/
    function setJSON() {
        var v_aJSON = [];
        var v_hObject = {};
        var v_hTempHash = {};
        var v_sKey = document.getElementById("user_email").value;
 // v_sKey = $_SESSION['user_email'];
        var v_sValue = document.getElementById("user_password").value;
        try {
            v_hObject[v_sKey] = v_sValue;
            document.getElementById("user_email").value = "";
            document.getElementById("user_password").value = "";
            if (g_objJSON == undefined) {
                v_aJSON.push(v_hObject);
            } else {
                v_hTempHash = mergeHashOb(g_objJSON[0], v_hObject);
      v_aJSON.push(v_hTempHash);
            }
    g_objJSON = v_aJSON;
    alert("Account successfully created!");
    for (var item in g_objJSON[0]) {
        console.log("Email: " + item + "nPassword: " +   g_objJSON[0][item]);
        $.ajax({
          url: "/open day planner/json.php",
          type: 'POST',
          data: {json: JSON.stringify(g_objJSON)},
          dataType: 'json'
        });
    }
        } catch (x) {
            alert(x.message);
  }
}
/** mergeHashOb - Merge a new JSON object with the global JSON object
           * @prm_hObj - Existing Hash object
           * @prm_hObj2 - New Hash object
           * Returns - A new Hash object contains the merged Hash objects
           **/
           function mergeHashOb(prm_hObj, prm_hObj2) {
                   var v_hObj = {};
                   for (var item in prm_hObj2) { 
                           v_hObj[item] = prm_hObj2[item]; 
                   }
                   return v_hObj;
           }`

JSON.php:`

<?php
   $json = $_POST['json'];
   /* sanity check */
   if (json_decode($json) != null)
   {
     $file = fopen('new_account_data.json','a');
     fwrite($file, $json);
     fclose($file);
   }
   else
   {
     // handle the error 
   }
?>

'

JSON输出: [{"c.harlie@gmail.com":"zxcvb"}][{"vrishgarg@xxxx.com":"vrish"}]

预期产出: [{"c.harlie@gmail.com":"zxcvb"}, {"vrishgarg@xxxx.com":"vrish"}]

您应该将 json 从文件中取出,并实际附加到该 json,而不是附加到文件的内容。我相信这样的事情会让你开始你想发生的事情。

<?php
    // let's parse this right away
    $json = json_decode($_POST['json']);
    /* sanity check */
    if ($json != null)
    {
      // parse the file contents to json
      $fileContents = file_get_contents('new_account_data.json');
      $parsedJson = json_decode($fileContents);
      if ($parsedJson === null) {
        // it's either the file contains bad json or it is empty (tested with 7.1)
        $parsedJson = array();
      }
      // append your new data to the parsed json
      // I'm assuming the $_POST['json'] returns a stringified array, I'll take the first element and append it.
      $parsedJson[] = $json[0];
      // now write to the file
      $file = fopen('new_account_data.json','w'); // note that we're writing, not appending.
      // write to file the json_encoded $parsedJson
      fwrite($file, json_encode($parsedJson));
      fclose($file);
    }
    else
    {
      // handle the error 
    }
?>

最新更新