【问题标题】:Uncaught SyntaxError: Unexpected token d in JSON at position 0 at JSON.parse (<anonymous>)未捕获的 SyntaxError:JSON.parse (<anonymous>) 位置 0 处的 JSON 中的意外标记 d
【发布时间】:2018-04-05 08:32:59
【问题描述】:

几个小时以来,我一直在疯狂地尝试使用 JSON.parse 从外部获取和显示 json 数据,但下面出现此错误

未捕获的 SyntaxError:JSON 中位置 0 处的意外标记 d 在 JSON.parse() 在 index.html:10

这是我迄今为止的代码和努力。有人可以帮我解决这个问题。我会感激的

 var test = JSON.parse ('data.json');
    console.log(test);

alert(test);





/*
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'data.json');

ourRequest.onload = function(){
    var ourData  = JSON.parse(ourRequest.responseText);
    console.log(ourData);
 console.log(ourData[0]);
alert(ourData);
};
ourRequest.send();
*/


</script>

数据.json

{
        name: "Sample Test",
        description: "This is a sample test paper to demonstrate the ReactJS UI design by components.",
        passCutoff: 0.33,       
        applyNegativeMarking: false,
        time: 1,
        questions: [
            {
            no: "1",
            qtext:"California is in which part of USA?",
            options:[
                {text:"East"},
                {text:"Mid"},
                {text:"West"},
                {text:"South"}
            ],
            ans:"West",
            marks: 3
        },
        {
            no: "2",
            qtext:"Who is Prime Minister of India?",
            options:[
                {text:"Sonia Gandhi"},
                {text:"Narendra Modi"},
                {text:"Manmohan Singh"},
                {text:"Rahul Gandhi"}
            ],
            ans:"Narendra Modi",
            marks: 2
        },
        {
            no: "3",
            qtext:"Which of the following is most popular Search Engine Company?",
            options:[
                {text:"Microsoft"},
                {text:"Facebook"},
                {text:"Google"},
                {text:"Yahoo"}
            ],
            ans:"Google",
            marks: 1
        },
        ]
    }

【问题讨论】:

  • 不能使用JONS.parse从服务器获取数据。
  • @FerhadOthman。请问我该怎么做
  • 查看下面的例子

标签: json


【解决方案1】:

$.getJSON 是异步的,所以你应该这样做:

$.getJSON("data.json", function(json) {
    console.log(json); // this will show the info it in firebug console
});

【讨论】:

    【解决方案2】:

    这是一个可以帮助你的例子:

    function loadJSON() {
      var http = new XMLHttpRequest();
      http.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var data=JSON.stringify(this.responseText);
            data=JSON.parse(data);
            console.log(data);
        }
      };
      http.open("GET", "data.json", true);
      http.send();
    }
    loadJSON()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-21
      • 1970-01-01
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 2018-12-09
      相关资源
      最近更新 更多