I have the following js string
var aaa='{a:1,b:2,c:3}';
How to quickly convert aaa into a standard Json object like {'a':1,'b':2,'c':3}
?
黄舟2017-05-18 11:00:23
You have a misunderstanding of the standard JSON object. The attributes of standard JSON are enclosed in double quotes. Neither single quotes nor single quotes will work.
JSON.parse(str)
The str parameter received here must be a string that conforms to the JSON format. If it does not conform to the JSON format, an error will be reported.
So first add double quotes to the properties of the object.
If you don’t want to use eval
, you can use this method,
var aaa="{a:1, b:2, c:3}";
function toJSONStr(str) {
return str.replace(/([$\w]+)\s*:/g, function(_, ){return '"'++'":'});
}
function toJSON(str) {
return JSON.parse(str);
}
toJSON(toJSONStr(aaa));
SyntaxError: JSON.parse: bad parsing
PHP中文网2017-05-18 11:00:23
JSON.parse(aaa);
JSON.stringify: json =》string
JSON.parse:string=》json
Please refer to: https://m.baidu.com/from=1086...