Parse JSON with no quotes in JavaScript

前端 未结 2 1441
长情又很酷
长情又很酷 2020-12-22 12:57

I get some JSON response that I want to parse and display on screen. The problem is that it comes sometimes with no quote around some of the string values. For example:

2条回答
  •  星月不相逢
    2020-12-22 13:34

    Well the best answer is fix the buggy code in the service that does it.

    So if you will not be able to use JSON.parse you can go old school and use eval or new Function.

    var x = '{foo:"bar", "cat" : "dog"}';
    eval("var o =" + x);
    console.log(o);
    

    or

    var x = '{foo:"bar", "cat" : "dog"}';
    var o = new Function("return " + x)();
    console.log(o)
    

    Use of these solutions opens you up to XSS attacks..

    Another option is write a regular expression that tries to fix it

提交回复
热议问题