Reputation: 165
This is what I have. I have an AJAX call that returns a string (data.d) like this:
{"id": "03100500", "name": "Book I"},{"id": "03100507", "name": "Book I - ALT"},{"id": "03100505", "name": "Book I - M"},{"id": "03100600", "name": "Book II"}
I've tried:
var books = JSON.parse(data.d);
Basically getting an error "Uncaught SyntaxError: Unexpected token , in JSON"
End result i'd like:
var newArray = [{"id": "03100500", "name": "Book I"},{"id": "03100507", "name": "Book I - ALT"},{"id": "03100505", "name": "Book I - M"},{"id": "03100600", "name": "Book II"}]
Not even sure if it's possible
Upvotes: 1
Views: 82
Reputation: 71
I think the missing [ was a copy and paste mistake. Assuming that, you are probably calling JSON.parse on an object. See image below:
Upvotes: 0
Reputation: 92440
Without the array delimiters, the string isn't valid JSON. Given the string without array delimiters, you can just add them before parsing:
let s = `{"id": "03100500", "name": "Book I"},{"id": "03100507", "name": "Book I - ALT"},{"id": "03100505", "name": "Book I - M"},{"id": "03100600", "name": "Book II"}`
// make new string with `[]` delimiters:
let o = JSON.parse('[' + s + ']')
console.log(o)
If the value is going to be flawed in more complicated ways like undelimited nested arrays, it will be harder and probably worth fixing it on the server if possible.
Upvotes: 4