簡體   English   中英

Json解析Node.js

[英]Json parsing nodejs

在解析json文件時需要幫助。 我需要從下面的文件中提取“選擇”。

{"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);
}
const choices = jsoncontent.questions.map(q => q.choices);

這將為您提供僅具有“ 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)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM