javascript - Convert a non-standard JS string into a standard json object
高洛峰
高洛峰 2017-05-18 10:58:23
0
3
476

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}?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
黄舟

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

洪涛

JSON.parse(aaa);

JSON.stringify: json =》string
JSON.parse:string=》json
Please refer to: https://m.baidu.com/from=1086...

Peter_Zhu
var result = eval('('+aaa+')');
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template