black_yurizan black_yurizan - 5 months ago 15x
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?


<div id="ex1"><h2>Example 1</h2><p></p><h4>results:</h4></div>


var message;

(function loadAjax()
{ var request;
if (window.XMLHttpRequest)
request = new XMLHttpRequest();

request = new ActiveXObject('Microsoft,XMLHTTP');

request.onreadystatechange = function()
if(request.readyState == 4 && request.status == 200)

message = request.responseText;
var obj = JSON.parse(message);
var text = obj.job[0].hospital;




"sex":{"male":{"fname":["Michael","Tom"]} ,"female":{"fname":["Alice","Katie"]}},
"job":["medical":{"hospital": "doctor"}, "education":{"school":"teacher"} ]


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 to learn more about the proper syntax for JSON.