search

Home  >  Q&A  >  body text

javascript - Convert a non-standard JS string into a standard json object

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

高洛峰高洛峰2777 days ago477

reply all(3)I'll reply

  • 黄舟

    黄舟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

    reply
    0
  • PHP中文网

    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...

    reply
    0
  • 天蓬老师

    天蓬老师2017-05-18 11:00:23

    var result = eval('('+aaa+')');

    reply
    0
  • Cancelreply