Parsing malformed JSON in JavaScript

前端 未结 5 612
别跟我提以往
别跟我提以往 2020-12-07 04:38

Thanks for looking!

BACKGROUND

I am writing some front-end code that consumes a JSON service which is returning malformed JSON. Specifically, the keys are n

5条回答
  •  Happy的楠姐
    2020-12-07 05:21

    You can avoid using a regexp altogether and still output a JavaScript object from a malformed JSON string (keys without quotes, single quotes, etc), using this simple trick:

    var jsonify = (function(div){
      return function(json){
        div.setAttribute('onclick', 'this.__json__ = ' + json);
        div.click();
        return div.__json__;
      }
    })(document.createElement('div'));
    
    // Let's say you had a string like '{ one: 1 }' (malformed, a key without quotes)
    // jsonify('{ one: 1 }') will output a good ol' JS object ;)
    

    Here's a demo: http://codepen.io/csuwldcat/pen/dfzsu (open your console)

提交回复
热议问题