现在几个小时我一直疯狂地尝试使用JSON.parse从外部获取和显示json数据,但是下面有这个错误
未捕获的SyntaxError:位于0的JSON中的意外标记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>
data.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
},
]
}
答案 0 :(得分:0)
$ .getJSON是异步的,所以你应该这样做:
$.getJSON("data.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
答案 1 :(得分:-1)
以下是一个可以帮助您的示例:
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()