Json解析nodejs
问题描述:
需要帮助解析json文件。我需要从下面的文件中提取'选择'。Json解析nodejs
{"questions":[
{"question1": "Who is Prime Minister of the United Kingdom?", "choices": ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"], "correctAnswer":0},
{"question": "North West", "choices": ["What is the name of Kim Kardashian's baby?", "What is the opposite of south?"], "correctAnswer":0},
{"question": "What's my favorite color?", "choices": ["Black", "Blue", "Magenta", "Red"], "correctAnswer":1},
{"question": "What's the meaning of life?", "choices": ["Too live happily", "To give to the greater good"], "correctAnswer":1}
]}
脚本的NodeJS:
var fs = require("fs");
fs.readFile(__dirname + "/lib/questions.json", "Utf-8", function(err, data){
jsoncontent = JSON.parse(data);
//console.log(jsoncontent);
for (var i = 0; i < jsoncontent.length; ++i) {
//code
}
});
如何提取?
答
尝试这样
var choiceList;
for (var i = 0; i < jsoncontent["questions"].length; ++i) {
//do what ever you want with choices
choiceList = jsoncontent["questions"][i]["choices"];
console.log(choiceList);
}
+0
我想你没有明白你的意思。你可以在这里看到,它给了你整个循环的每一行 –
答
const choices = jsoncontent.questions.map(q => q.choices);
这会给你只用 “选择” 属性数组。
jsoncontent.questions.forEach(q => console.log(q));
这将打印出“选择”。
const jsoncontent = {
"questions":[
{
"question1": "Who is Prime Minister of the United Kingdom?",
"choices": ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
"correctAnswer":0
},
{
"question": "North West",
"choices": ["What is the name of Kim Kardashian's baby?", "What is the opposite of south?"],
"correctAnswer":0
},
{
"question": "What's my favorite color?",
"choices": ["Black", "Blue", "Magenta", "Red"],
"correctAnswer":1
},
{
"question": "What's the meaning of life?",
"choices": ["Too live happily", "To give to the greater good"],
"correctAnswer":1
}
]}
const choices = jsoncontent.questions.map(q => q.choices);
console.log(choices);
jsoncontent.questions.forEach(q => console.log(q));
中示出预期结果来定义'extract'。同时显示您用来自己解决这个问题的代码。这不是一个代码写入服务,你需要显示你的尝试。 – charlietfl