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 badges2 Answers
Reset to default 8The \
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
版权声明:本文标题:javascript - JSON.parse failing - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744774488a2624542.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论