Parsing string as JSON with single quotes?

后端 未结 7 907
走了就别回头了
走了就别回头了 2020-11-22 10:22

I have a string

str = \"{\'a\':1}\";
JSON.parse(str);
VM514:1 Uncaught SyntaxError: Unexpected token \'(…)

How can I parse the above stri

相关标签:
7条回答
  • 2020-11-22 10:31

    Using single quotes for keys are not allowed in JSON. You need to use double quotes.

    For your use-case perhaps this would be the easiest solution:

    str = '{"a":1}';
    

    Source:

    If a property requires quotes, double quotes must be used. All property names must be surrounded by double quotes.

    0 讨论(0)
  • 2020-11-22 10:34
    json = ( new Function("return " + jsonString) )(); 
    
    0 讨论(0)
  • 2020-11-22 10:41

    If you are sure your JSON is safely under your control (not user input) then you can simply evaluate the JSON. Eval accepts all quote types as well as unquoted property names.

    var str = "{'a':1}";
    var myObject = (0, eval)('(' + str + ')');
    

    The extra parentheses are required due to how the eval parser works. Eval is not evil when it is used on data you have control over. For more on the difference between JSON.parse and eval() see JSON.parse vs. eval()

    0 讨论(0)
  • 2020-11-22 10:41

    Something like this:

    var div = document.getElementById("result");
    
    var str = "{'a':1}";
      str = str.replace(/\'/g, '"');
      var parsed = JSON.parse(str);
      console.log(parsed);
      div.innerText = parsed.a;
    <div id="result"></div>

    0 讨论(0)
  • 2020-11-22 10:46

    I know it's an old post, but you can use JSON5 for this purpose.

    <script src="json5.js"></script>
    <script>JSON.stringify(JSON5.parse('{a:1}'))</script>
    
    0 讨论(0)
  • 2020-11-22 10:46
    var str =  "{'a':1}";
    str = str.replace(/'/g, '"')
    obj = JSON.parse(str);
    console.log(obj);
    

    This solved the problem for me.

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