如何以适当的json格式动态创建JSON并继续将新数据附加到同一对象?

时间:2018-03-14 02:05:14

标签: javascript php 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"}]

1 个答案:

答案 0 :(得分:0)

你应该从文件中取出 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 
    }
?>