简体   繁体   中英

Json parsing nodejs

Need help in parsing json file. I need to extract 'choices' from the file below.

{"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 script:

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

}

});

How to extract?

try like this

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);

That will give you an array with just the "choices" properties.

jsoncontent.questions.forEach(q => console.log(q));

That will print out "choices".

 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)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM