简体   繁体   中英

Why this JSON object cannot be parsed?

In my JavaScript file,

The declaring and json parse for the ajax response text is like this:

var subcats = JSON.parse(this.responseText);

The supposed responseText for the parsing is like this:

{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"}{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}

and it gives me this error:

SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 2 column 64 of the JSON data

what's the syntax error? help

Your JSON have multiple elements and therefore should be wrap in an Array/List like this

[{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"}{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}]

Hope it helps

Your JSON is invalid. You need change it like this:

[{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"},{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}]

your JSON data is invalid so that you are having problem,

 var temp=[]; temp=[{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"},{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}] console.log(JSON.stringify(temp)) 

Your JSON have multiple elements. So it must be treated like Array. See below image.

Below is valid JSON structure.

[{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"},{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}]

在此处输入图片说明

The JSON.parse () method parses a JSON string, constructing the JavaScript value or object described by the string. So you can use it like this if you have a single item:

JSON.parse('{"presubcatId":"1", "precatId":"1", "presubcatName":"HR Manager"}');

but in your case you have multiple items that should be wrapped inside brackets [] and separated by commas or there is SyntaxError:

JSON.parse('[{"presubcatId":"1", "precatId":"1", "presubcatName":"HR Manager" }, { "presubcatId": "2", "precatId": "1", "presubcatName": "Marketing Manager"}]');

 var string = '[{"presubcatId":"1", "precatId":"1", "presubcatName":"HR Manager" }, { "presubcatId": "2", "precatId": "1", "presubcatName": "Marketing Manager"}]'; var json = JSON.parse(string); console.log(json); 

Your json object is not a valid json. You can check it on this site. It helps me a lot when I need to format or validate a Json object.

https://jsonlint.com/

Here is your json object formatted and it says what you are missing.

Json通过jsonlint验证

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM