JavaScript

Parse JSON string, cross browser

JSON stands for JavaScript Object Notation. You would think it would be second nature to parse those strings from your Ajax request, but not so much for older browsers. The modern browsers do have the JSON api that makes it very easy to work with:

JSON.parse(jsonString); // Voila

But if you want to have support on all browsers, you would have to add some extra code to make it work. The problem arises when the user add unsecure code to the data string. We don't want to arbitrarily run any code that is sent to us. We want to make sure we remove any thing that doesn't conform to the JSON standard first. So here goes:

var parseJSON = function (data) {
    if (window.JSON){
        return window.JSON.parse(data);
    }else {
        var jsoner = {};
        data = data.replace(/^\s+/,"").replace(/\s+$/,""); // Trim the string
        json = (function (jsstring) {
            // Borrowed from jquery 1.7.1
            var rvalidchars = /^[\],:{}\s]*$/,
            rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
            rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
            rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
            if (rvalidchars.test(data.replace( rvalidescape, "@" )
                    .replace( rvalidtokens, "]" )
                    .replace( rvalidbraces, ""))){
                return ( new Function( "return " + data ) )();
            }
        })();
        if (!json){
            throw new Error("Invalid JSON string");
        }
        return json;
    }
}

Now you can parse JSON in Firefox as well as IE7. Enjoy!


Comments

There are no comments added yet.

Let's hear your thoughts

For my eyes only