简体   繁体   English

JSON:解析时出错

[英]JSON: Error while Parsing

I've the following JSON (Valid) sting. 我有以下JSON (有效)字符串。

[["abc","{\"icon\":\"adjust\",\"prefix\":\"fa\",\"markerColor\":\"red\"}"],["xyz","{\"icon\":\"archive\",\"prefix\":\"fa\",\"markerColor\":\"green\"}"],["azs","{\"icon\":\"asterisk\",\"prefix\":\"fa\",\"markerColor\":\"darkred\"}"]]

it gives error when I try to Parse using the JSON.parse function here is the code that I'm using for parsing. 当我尝试使用JSON.parse函数进行解析时,它给出了错误,这是我用于解析的代码。

JSON.parse('[["abc","{\"icon\":\"adjust\",\"prefix\":\"fa\",\"markerColor\":\"red\"}"],["xyz","{\"icon\":\"archive\",\"prefix\":\"fa\",\"markerColor\":\"green\"}"],["azs","{\"icon\":\"asterisk\",\"prefix\":\"fa\",\"markerColor\":\"darkred\"}"]]');

and it gives an error in console Uncaught SyntaxError: Unexpected token i 并在控制台中显示错误Uncaught SyntaxError: Unexpected token i

here is the Correct Output by same string using online JSON viewer. 这是使用在线JSON查看器按相同字符串正确输出的信息。 使用在线JSON查看器按相同的字符串更正输出

When you use JSON viewer, it's different from when you use the code in your JS code. 使用JSON查看器时,与使用JS代码中的代码不同。 Like @Jonathan stated, you should double escape you json sting. 就像@Jonathan所说的那样,您应该将json字符串加倍转义。

 JSON.parse('[["abc","{\\\\"icon\\\\":\\\\"adjust\\\\",\\\\"prefix\\\\":\\\\"fa\\\\",\\\\"markerColor\\\\":\\\\"red\\\\"}"],["xyz","{\\\\"icon\\\\":\\\\"archive\\\\",\\\\"prefix\\\\":\\\\"fa\\\\",\\\\"markerColor\\\\":\\\\"green\\\\"}"],["azs","{\\\\"icon\\\\":\\\\"asterisk\\\\",\\\\"prefix\\\\":\\\\"fa\\\\",\\\\"markerColor\\\\":\\\\"darkred\\\\"}"]]'); 

Your json structure is invalid. 您的json结构无效。 You should use this instead(without slashes): 您应该改用它(不使用斜线):

  '[["abc",["icon":"adjust","prefix":"fa","markerColor":"red"]],["xyz",["icon":"archive","prefix":"fa","markerColor":"green"]],["azs",["icon":"asterisk","prefix":"fa","markerColor":"darkred"]]'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM