如何从作为对象的JSON导入和使用数据?

时间:2017-04-27 19:14:35

标签: javascript arrays json object

以前我从JSON导入数据wihch是一个数组,这不是一个问题。现在我有一个问题,因为我的变量是一个对象。我想将所有问题都推送到数组中,然后在html文档中显示它们。 JSON文件的链接在代码上。

和JS代码。



const myjson = 'http://tnij.xyz/bj5'; // LINK TO JSON FILE!
const questions = [];
fetch(myjson)
    .then(blob => blob.json('questions'))
    .then(data => questions.push(data))

console.log(questions);




2 个答案:

答案 0 :(得分:0)

(注意:由于跨域问题,我无法运行代码段)

我认为您需要做的是.concat传入的值或使用.apply。就个人而言,我选择.concat



const myjson = 'http://tnij.xyz/bj5'; // LINK TO JSON FILE!
const questions = [];
fetch(myjson)
    .then(blob => blob.json('questions'))
    .then(data => {
        questions = quest.concat(data);
        console.info(questions);
    });




另请注意,questions链之外的fetch将为空。

答案 1 :(得分:0)

一些观察结果:

  • http://tnij.xyz/bj5返回属性为questionsarray的对象时,为什么还要将其推送到数组
  • 您可以使用jsonObj.questions直接访问问题数组。此处,jsonObj是您要回复的完整JSON对象。
  • 您可以在HTML中追加问题和答案,例如



var questions = [
    {
      "id": 1,
      "question": "Obwód trójkąta ABC wynosi 20cm. Jaką długość ma podstawa AB?",
      "answers": [
        {
          "id": 1,
          "answer": "8.4 cm",
          "correct": true
        },
        
        {
          "id": 2,
          "answer": "5.8 cm",
          "correct": false
        },
        
        {
          "id": 1,
          "answer": "0.6 cm",
          "correct": false
        },
        
        {
          "id": 1,
          "answer": "1.2 cm",
          "correct": false
        }
      ]
    }];
    
for(var i in questions) {
  document.getElementById('questions').innerHTML = questions[i].question;
  var answers = document.getElementById("answers");
  for(var j in questions[i].answers) {
    var label = document.createElement("label");
    var radio = document.createElement("input");
    radio.type = "radio";
    radio.name = "choices";
    radio.value = questions[i].answers[j].correct;
    label.appendChild(radio);
    label.appendChild(document.createTextNode(questions[i].answers[j].answer));
    answers.appendChild(label);
  }
}

<div id="questions">
</div>
<div id="answers"></div>
&#13;
&#13;
&#13;