如何将 json 键解析为 json 对象

How do I parse json keys into json objects

所以我在尝试转换诸如

之类的内容时遇到了这个问题
[0]['question']: "what is 2+2",
[0]['answers'][0]: "21",
[0]['answers'][1]: "312",
[0]['answers'][2]: "4"

进入一个实际格式化的 json 对象,就像这样

[
  {
    'question': 'what is 2+2',
    'answers': ["21", "312", "4"]
  }
]

但我不太确定要采取什么方法来完成这项工作。

我正计划通过 javascript 解析第一个片段中的键值并将其解码为 json 对象,就像在 python 的第二个片段中一样。

你知道怎么做吗?我会接受几乎任何语言的例子,因为阅读它们背后的概念应该不会太担心。

像这样。您需要处理输入错误。

获取数据结构并根据输入向其添加内容的函数

function add(old, input) {
  var index = input[0];
  var section = input[1];
  if (old[index] == undefined) {
    old[index] = {}
  };
  if (section == "question") {
    old[index]['question'] = input[2];
  }

  if (section == "answers") {
    var answerIndex = input[2];
    var answerValue = input[3];

    if (old[index]["answers"] == undefined) {
      old[index]["answers"] = []
    };

    old[index]["answers"][answerIndex] = answerValue
  }

  return old;
}

一些输入:

var inputs = [[0, "question", "what"],
              [0, "answers", 0, "21"],
              [0, "answers", 1, "22"]];

var result = {};

inputs.forEach(function(input) { add(result, input) })

JSON.stringify(result)


"{"0":{"question":"what","answers":["21","22"]}}"

我认为您应该按如下格式设置 json:

{
    "questions": [
        {
            "question": "What is 2+2",
            "possible_answers": [
                {
                    "value": 1,
                    "correct": false
                },
                {
                    "value": 4,
                    "correct": true
                },
                {
                    "value": 3,
                    "correct": false
                }
            ]
        },
        {
            "question": "What is 5+5",
            "possible_answers": [
                {
                    "value": 6,
                    "correct": false
                },
                {
                    "value": 7,
                    "correct": false
                },
                {
                    "value": 10,
                    "correct": true
                }
            ]
        }
    ]
}

为此,你可以做到:

var result = {}
result.questions = []; //the questions collection

var question = {};    //the first question object
question.question = "what is 2 + 2";      
question.possible_answers = [];

var answer1 = {};
answer1.value = 1;
answer1.correct = false;

var answer2 = {};
answer2.value = 2;
answer2.correct = true;

var answer3 = {};
answer3.value = 3;
answer3.correct = false;

question.possible_answers.push(answer1);
question.possible_answers.push(answer2);
question.possible_answers.push(answer3);

result.questions.push(question); //add the first question with its possible answer to the result.

您可以使用 jsonlint 来帮助自己格式化 json,然后尝试设置您的 javascript 对象以获得您想要的 json。

希望能帮到你!