Parse JSON with no quotes in JavaScript

前端 未结 2 1440
长情又很酷
长情又很酷 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

    0 讨论(0)
  • 2020-12-22 13:50

    Some observations :

    • JSON coming from the server is not a valid JSON as it is having a string value without quotes(").

    This issue should be corrected from server side only. So, that you will get the valid JSON in response like below.

    0 讨论(0)
提交回复
热议问题