Search code examples
javascriptjsonprototypejs

convert "converted" object string to JSON or Object


i've following problem and since i upgraded my prototypeJS framework.

the JSON parse is not able anymore to convert this string to an object.

"{empty: false, ip: true}"

previously in version 1.6 it was possible and now it needs to be a "validated" JSON string like

'{"empty": false, "ip": true}'

But how can i convert the 1st example back to an object?


Solution

  • JSON needs all keys to be quoted, so this:

    "{empty: false, ip: true}"
    

    is not a valid JSON. You need to preprocess it in order to be able to parse this JSON.

    function preprocessJSON(str) {
    
        return str.replace(/("(\\.|[^"])*"|'(\\.|[^'])*')|(\w+)\s*:/g,
        function(all, string, strDouble, strSingle, jsonLabel) {
            if (jsonLabel) {
                return '"' + jsonLabel + '": ';
            }
            return all;
        });
    
    }
    

    (Try on JSFiddle) It uses a simple regular expression to replace a word, followed by colon, with that word quoted inside double quotes. The regular expression will not quote the label inside other strings.

    Then you can safely

    data = JSON.parse(preprocessJSON(json));