如何在JSON中分隔每个变量

时间:2018-06-05 13:42:20

标签: javascript json ajax

所以,我有一个显示我的JSON的ajax调用:

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

但我想这样:

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

我想要添加的唯一内容是“id”:“new”。

这是我的ajax调用(我的JSON开始看起来像我的ajax调用的第一个)

 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) {
              window.location = 'index.php';
          });
 });
}

编辑:Ouni希望我展示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;
} // } 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;
} // closing off the else statement
$newExerciseData['main_object'] = $database['data'];
header('Content-Type: application/json');
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));
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
} //closing off the if isset.

怎么能实现这个目标?我知道这不是我的saveJson.php问题。我知道这是我的ajax调用,因为当我添加id时,它开始像第一段JSON代码一样显示:getUrlParameter('id')

2 个答案:

答案 0 :(得分:0)

只关注您自己的问题而不考虑对整体方法做出的完全有效的评论,看起来您有一个查询字符串格式的数据,并且您希望将其解析为JSON格式。 quesrystring格式是这样的数据:

language=nl_NL&getExerciseTitle=test

你最终想要这个:

{
  language: "nl_NL",
  getExerciseTitle: "test"
}

等等。

实现此目的的一种方法是使用现有的库,为您精确地执行此操作。例如,query-string包。

例如,给定一个字符串:

 const result = "language=nl_NL&getExerciseTitle=test";
 const parsed = queryString.parse(result);

将产生您期望的结果。

答案 1 :(得分:0)

以下是如何使用vanilla JavaScript解析查询字符串,而无需安装第三方软件包:

const start = {"main_object":{"id":"new","formData":"language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablescounter%5B1%5D=test"}}
const temp = Object.assign({}, start);
temp.formData = decodeURIComponent(start.main_object.formData)
  .split("&")
  .reduce((result, data) => {
    const components = data.split("=");
    let prop_name = components[0];
    const prop_value = components[1];
    const array_char_index = prop_name.indexOf('[');

    if (array_char_index > 0) {
      prop_name = prop_name.substring(0, array_char_index);
      if (result[prop_name] === undefined) { result[prop_name] = []; }
      result[prop_name].push(prop_value);
    }
    else {
      result[prop_name] = prop_value;
    }
    return result;
  }, {})
;
console.log(temp.formData);

我建议尽可能使用vanilla JS,这样您就可以学习这些概念,这样当您发现自己需要更多时,就可以根据自己的需要进行调整。