black_yurizan black_yurizan - 7 months ago 41
Javascript Question

JSON.parse: expected ',' or '}' after property value in object

I keep getting this error message when I call my human.json file with ajax. The whole error message reads JSON.parse: expected ',' or '}' after property value in object at line 2 column 22 of the JSON data. I looked online for it, and there have been people who had similar error messages, however, they are not calling from ajax. In addition to that, they are not nesting arrays within objects within objects. I think that is the reason why I am getting this error message. Are you not allowed to nest that many properties into each other? Here is my code.

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.age;
attach('ex1',text,'p');
}
}

request.send();

})();


JSON File

{
"sex": {
"male": {
"fname": [
"Michael",
"Tom"
]} ,
"female"
},
"age": [
16,
80
],
"job":[]
}

Answer

Your JSON file has a syntax error. The following is reformatted to highlight the error:

{
 "sex":{
  "male":{"fname":["Michael","Tom"]},
  "female"        <----------------- SYNTAX ERROR
 },
 "age":[16,80],
 "job":[]
}

In JSON, objects have the syntax:

{"name" : "value"}

The syntax {"foo"} is invalid according to JSON spec. Therefore you need to provide some value for the female attribute:

{
 "sex":{
  "male":{"fname":["Michael","Tom"]},
  "female":{}
 },
 "age":[16,80],
 "job":[]
}
Comments