我收到此错误消息:
SyntaxError: JSON.parse: expected ',' or ']' after array element at line 4 column 18 of the JSON data.
我认为这是因为我在数组中有一个对象,也许这是不允许的。但我需要经验丰富的开发人员对此进行确认。你能把对象放在 json 的数组中吗?
HTML
<div id="ex1"><h2>Example 1</h2><p></p><h4>results:</h4></div>
Javascript
var message;
(function loadAjax()
{ var request;
if (window.XMLHttpRequest)
{
request = new XMLHttpRequest();
}
else{
request = new ActiveXObject('Microsoft,XMLHTTP');
}
request.open('GET','human.json');
request.onreadystatechange = function()
{
if(request.readyState == 4 && request.status == 200)
{
message = request.responseText;
var obj = JSON.parse(message);
var text = obj.job[0].hospital;
attach('ex1',text,'p');
}
}
request.send();
})();
JSON
{
"sex":{"male":{"fname":["Michael","Tom"]} ,"female":{"fname":["Alice","Katie"]}},
"age":[16,80],
"job":["medical":{"hospital": "doctor"}, "education":{"school":"teacher"} ]
}
最佳答案
这是不正确的:
"job":["medical":{"hospital": "doctor"}, "education":{"school":"teacher"} ]
这是正确的:
"job": {"medical": {"hospital": "doctor"}, "education": {"school": "teacher"} }
请注意,我将 []
更改为 {}
方括号用于数组(许多单独的项目)。示例:
{ "my_array": [1, 2, "three"] } <-- Notice that the items in square brackets
so not assign a value such as "key": "value"
curl 用于关联条目(许多 "key": "value"
项)。示例:
{ "my_association": { "dogs": "rule", "cats": "drool" } }
请引用JSON.org了解有关 JSON 正确语法的更多信息。
关于javascript - JSON.parse 数组嵌套元素不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37033317/