简体   繁体   中英

Console throwing JSON.parse error with an Array

So, my JSON response is a simple array:

[35,55]

Chrome network inspector shows it as valid JSON. However, when I use JSON.parse on the xhr.responseText it gives me the error: Uncaught SyntaxError: Unexpected token :

I've tried using JSON.stringify and just using it without parsing it in JSON.parse, but then it isn't being seen as an array by JS.

JSONLint says it's valid JSON too.

I'm not sure what to do, I just want to use my xhr array as an array in JS.

I faced this error twice while working with my app. Ofcourse I had a complex Json and not simple as yours. Below are the two scenarios. Please check that none of them matches your case. a. As I said I was using complex json, I missed out in using "," and sometime I used curly braces to define an array. b. I had to confirm that js object with one class. My json had 2 more extra values than the class. So it was unable to parse it. Hope this experience helps!

The issue was that I was using JSON.parse to pass a variable which had already been parsed by JSON.parse to a storage variable, which resulted in the error.

Here is an example of what I did wrong:

var currentJSON = JSON.parse(xhr.responseText);
var oldJSON = [];
if (currentJSON) {
    /* do stuff with currentJSON, like compare currentJSON with oldJSON */
    oldJSON = JSON.parse(currentJSON); /* <- THIS is what caused the issue */
}

Here is what I was supposed to do:

var currentJSON = JSON.parse(xhr.responseText);
var oldJSON = [];
if (currentJSON) {
    /* do stuff with currentJSON, like compare currentJSON with oldJSON */
    oldJSON = currentJSON; /* <- removed JSON.parse(); from currentJSON */
}

问题出在我两次解析JSON。

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