admin管理员组

文章数量:1277344

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?

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?

Share Improve this question edited Apr 14, 2013 at 21:26 Dave 46.3k12 gold badges70 silver badges108 bronze badges asked Apr 14, 2013 at 21:18 Anton GildebrandAnton Gildebrand 3,70713 gold badges52 silver badges92 bronze badges 1
  • Don't use string literals containing JSON! Use object literals instead. – Bergi Commented Apr 14, 2013 at 21:28
Add a ment  | 

2 Answers 2

Reset to default 6

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.)

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 es from this part:

"material": "Gummislang 3/4"30m

The " needs to be escaped.

本文标签: javascriptTrying to parse JSON stringunexpected numberStack Overflow