Reputation: 3707
I am trying to parse this JSON:
var json = '{"material":"Gummislang 3\/4\" 30 m (utanp\u00e5liggande sk\u00e5p)"}'
I run JSON.parse(json)
but i get the error SyntaxError: Unexpected number
when doing so. I have tried this in Google Chrome. I don't know what the problem is since I can take the JSON string and put it in any JSON validator and it claims that the JSON is valid. Shouldn't the browser be able to parse it?
Upvotes: 3
Views: 8007
Reputation: 32072
You are inserting a JSON object representation into a JavaScript string without properly escaping the representation.
To avoid having to do this, remove the quotes you are adding around the representation, and skip the JSON.parse(json)
– the default output from PHP's json_encode()
is valid JavaScript when used in this context.
For security, you should specify the JSON_HEX_TAG
option if possible. This will prevent cross-site scripting in cases where the JSON might end up inside a document parsed as XML. (And for XML documents, the JSON should be inside a CDATA section as well.)
Upvotes: 6
Reputation: 887405
You're validating the string literal, which is a valid JSON string containing invalid JSON. You need to validate the value of the string, which is not valid JSON.
If you paste the string value into a JSON validator, you'll see that the error comes from this part:
"material": "Gummislang 3/4"30m
The "
needs to be escaped.
Upvotes: 4