admin管理员组

文章数量:1392003

I'm trying to create a JavaScript object from a JSON string "object" but it fails with the error:

"SyntaxError: JSON.parse: expected ',' or '}' after property value in object at line 1 column 48 of the JSON data"

var jsobj = JSON.parse( '{"lineID":11,"siteID":3,"mystring":"this is a \"Test\" string with quotes"}' );

I'm trying to create a JavaScript object from a JSON string "object" but it fails with the error:

"SyntaxError: JSON.parse: expected ',' or '}' after property value in object at line 1 column 48 of the JSON data"

var jsobj = JSON.parse( '{"lineID":11,"siteID":3,"mystring":"this is a \"Test\" string with quotes"}' );

mystring is a string which includes double quotes but I've escaped them correctly with the backslash. Why would it fail?

I noticed it passes OK on this online JSON parsing site: json parser

Share Improve this question asked May 23, 2018 at 14:00 PapillonUKPapillonUK 6528 silver badges20 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

The \ character is an escape character for JavaScript and JSON.

When the JavaScript parser parses the string literal it turns \" in the JavaScript source code into " in the string.

When the JSON parser parses the string, it finds an unescaped " and errors.

To include \" in the JSON data, you need to escape the \ in the JavaScript string literal: \\".

var jsobj = JSON.parse('{"lineID":11,"siteID":3,"mystring":"this is a \\"Test\\" string with quotes"}');
console.log(jsobj);


Nesting data formats is always a pain. It is best to avoid doing that whenever possible.

It doesn't make sense to have a string literal containing JSON in JavaScript in the first place.

JSON is a subset of JavaScript. Just use the JSON as a JavaScript literal.

var jsobj = {
  "lineID": 11,
  "siteID": 3,
  "mystring": "this is a \"Test\" string with quotes"
};

console.log(jsobj);

For double quotes you have to use double backslash

var jsobj = JSON.parse( '{"lineID":11,"siteID":3,"mystring":"this is a \\"Test\\" string with quotes"}' );

this should work

本文标签: javascriptJSONparse failingStack Overflow