2016-07-14 5 views
0

jsonファイルの解析に助けが必要です。私は以下のファイルから「選択肢」を抽出する必要があります。Json parsing nodej

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