missing quotation marks on keys in JSON

后端 未结 2 1182
梦如初夏
梦如初夏 2020-12-19 16:27

I have a string containing malformed JSON which is being provided to me where the keys are missing the quotation marks. The structure of the JSON is out of my control, so I

2条回答
  •  太阳男子
    2020-12-19 17:10

    If the only thing wrong with the JSON is property names without quotes, then it is still a valid JavaScript object literal even though it isn't valid JSON.

    So, if you trust the source, you can wrap the text in parentheses and eval it.

    This will be simpler and more reliable than any regular expression.

    Example:

    var badJSON = '{ a: "b" }';
    var obj = eval( '(' + badJSON + ')' );
    console.log( obj );    // Logs: Object {a: "b"}
    console.log( obj.a );  // Logs: b
    

提交回复
热议问题