如何将json密钥解析为json对象

时间:2015-03-18 14:15:40

标签: javascript python json decode encode

所以我遇到了这个问题,我试图转换某些内容,例如

[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一样。

您对如何做到这一点有任何想法吗?我几乎接受任何一种语言的例子,因为阅读它们背后的概念并不是一件令人担忧的事。

2 个答案:

答案 0 :(得分:1)

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

根据输入

获取数据结构并向其添加内容的函数
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"]}}"

答案 1 :(得分:0)

我认为你应该按照以下方式格式化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。

希望帮助你!