如何更改我的JSON外观

时间:2018-06-06 07:36:40

标签: javascript php json ajax

我有一个AJAX调用,让我的JSON在我的JSON文件中看起来:

{
  "main_object": {
    "id": "new",
    "formData": "language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablescounter%5B1%5D=test"
  }
}

但是我想这样(这是在我改变我的AJAX调用之前:id: getUrlParameter('id')

{
  "main_object": {
    "language": "nl_NL",
    "getExerciseTitle": "asd",
    "question_takeAudio_exerciseWord": ["asd"],
    "Syllablescounter": ["ASDasd", ""]
  }
}

我要添加的唯一内容是"id": "new",但是当我这样做时(使用id: getUrlParameter('id')它会获取ID,但它会弄乱我的代码。

这是我的AJAX调用(当我使用它时,我的JSON开始看起来像第一段代码)

function saveExerciseAjaxCall() {
  $("#my_form").on("submit", function(event) {
    event.preventDefault();
    $.ajax({
      url: 'saveJson.php',
      type: 'POST',
      data: {
        id: getUrlParameter('id'),
        formData: $('#my_form').serialize()
      },
      dataType: 'json',
    }).done(function(response) {

    });
  });
}

如何实现这一目标?我知道这不是我saveJson.php的问题。我知道这是我的AJAX调用,因为它在我添加id: getUrlParameter('id')时开始显示为第一段JSON代码。

编辑:因为有人说它可能是我的PHP代码..这是我的PHP代码:

<?php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
    $newExerciseData['main_object'] = $data;
    $exerciseArray = $data['main_object'];
    $databaseFile = 'json_files/database.json';
    $textContent = file_get_contents($databaseFile);
    $database = json_decode($textContent, true);
    if ($data['id'] === 'new') {
        if (count($database['data']) == 0) {
            $ID = 0;
        } // ending database['data'] count 0.
        else {
            $maxID = max($database['data']);
            $ID = ++$maxID["id"];
         } // ending the max ID else statement.
        $newJsonFile = 'jsonData_' . $ID . '.json';
        $newJsonFilePath = 'json_files/' . $newJsonFile;
        //Create new database exercise_txt
        $newArrayData = array(
        'id' => $ID,
        'exercisetitle' => $data['formData']['getExerciseTitle'],
        'language' => $data['formData']['language'],
        'file' => $newJsonFile
    );
    $database['data'][] = $newArrayData;
    file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
    file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
} // } op regel 34 lijkt verdwaald...?
else {
    $index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
    $correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
    $newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
    $newJsonFilePath = 'json_files/' . $newJsonFile;
    //Create new database exercise_txt
    $newArrayData2 = array(
        'id' => (int) $data['id'],
        'exercisetitle' => $data['formData']['getExerciseTitle'],
        'language' => $data['formData']['language'],
        'file' => $newJsonFile
    );
    $database['data'][$index] = $newArrayData2;
    file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE));
    file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE));
} // closing off the else statement
 echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
} //closing off the if isset.
?>

2 个答案:

答案 0 :(得分:0)

您可以使用parse_str($str, $output);它可以帮助您实现所需。 请注意,parse_str接受两个参数,第一个是字符串(get Parameters),第二个是返回结果的数组。你可以使用以下代码

parse_str($str, $output); echo json_encode($output);

答案 1 :(得分:0)

问题是如何处理formData参数。 serialize()正在构建url编码的字符串,但是您需要键值对。试试这个:

$("#my_form").on("submit", function(event) {
    event.preventDefault();
    var myData = {id: getUrlParameter('id')};
    for (var pair of formData.entries()) {
        myData[pair[0]] = pair[1]; 
    }
    $.ajax({
      url: 'saveJson.php',
      type: 'POST',
      data: myData,
      dataType: 'json',
   }).done(function(response) {
      window.location = 'index.php';
   });
 });
}