black_yurizan black_yurizan - 7 months ago 21
Javascript Question

JSON.parse array nested element not working

I am getting this error message:


SyntaxError: JSON.parse: expected ',' or ']' after array element at line 4 column 18 of the JSON data.


I think it is because I have an object within an array, and maybe that is not allowed. But I need confirmation of this from experienced developers. Can you put objects in arrays in 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"} ]
}

Answer

This is incorrect:

"job":["medical":{"hospital": "doctor"}, "education":{"school":"teacher"} ]

This is correct:

"job": {"medical": {"hospital": "doctor"}, "education": {"school": "teacher"} }

Notice I changed the [] to {}

Square brackets are used for arrays (many individual items). Example:

{ "my_array": [1, 2, "three"] }      <-- Notice that the items in square brackets
                                         so not assign a value such as "key": "value"

Curlies are used for associative entries (many "key": "value" items). Example:

{ "my_association": { "dogs": "rule", "cats": "drool" } }

Please refer to JSON.org to learn more about the proper syntax for JSON.