2016-07-14 78 views
0

需要幫助解析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 

} 

}); 

如何提取?

+1

中示出預期結果來定義'extract'。同時顯示您用來自己解決這個問題的代碼。這不是一個代碼寫入服務,你需要顯示你的嘗試。 – charlietfl

回答

0

嘗試這樣

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

我想你沒有明白你的意思。你可以在這裏看到,它給了你整個循環的每一行 –

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