JSON Parsing and Stringifying in jQuery (as a plugin)

jQuery has many kick-ass javascript utilities. Among these is a method (jQuery.getJSON()) that parses JSON that you grab from a remote source and gives it back to you as a JSON object. Excellent!

Surprisingly though, jQuery (as of 1.3, to my knowledge anyway) does not make any functions available to allow you to securely parse a simple text string into JSON. Not sure why this is so, especially since they must do it behind the scenes for the getJSON() method, but so be it.

I needed this functionality, though, so I could pass some data from one of my templates to a jQuery function I’m working on.

Fortunately, even though jQuery doesn’t have built-in functionality for this, it was relatively trivial to wrap the open source JSON parsing and stringifying library published by JSON.org in an easy-to-use jQuery plugin.

So that’s what I did. I changed nothing of the JSON parsing library implementation published by JSON.org; I just wrapped two jQuery methods around it, as follows:

;(function($) {
    if (!this.JSON) {
        var JSON = {};
    }
    /* ... implementation of parse() and stringify() here ... */
    $.toJSON = function(text, reviver) {
        if (typeof reviver == "undefined") {
            reviver = null;
        }
        return JSON.parse(text, reviver);
    };
    $.jSONToString = function(value, replacer, space) {
        if (typeof replacer == "undefined") {
            replacer = null;
        }
        if (typeof space == "undefined") {
            space = null;
        }
        return JSON.stringify(value, replacer, space);
    };

})(jQuery);

Pretty convenient. Now I can securely parse and decode JSON to my heart’s content.

Here’s the source code of the full jQuery JSON plugin, if you’re interested. Note that I have not extensively tested the plugin, but since I did not actually touch any part of the JSON parsing library it’s based on (save for creating a local scope for the JSON variable), I wouldn’t foresee any issues.

Here’s a bit more information about the library the plugin is based on.

13 comments

  1. Mark

    Hi,
    I get success in Safari and FF, but in IE I’m getting:
    JSON is null or not a object line 347.
    Attempted to call
    var jsonStr = $.jSONToString(jsonObj, null, “ ”);

    Trying to figure out if that means the xmlObjectifier (turning XML to JSON) or if something is goofed up.

    Thanks for this though.

  2. Mark

    Looks like its the xmlObjectifier from teracoder. I’ll go back up that tree.

    Thanks

  3. Jim Dalton

    Thanks Mark. If it does end up being a bug in the code here, please do let me know. Like I said, I literally wrapped the code from JSON.org without touching it, so I’m hoping it’s unlikely there’s a bug in the code here.

  4. Mark

    Hi,
    Actually if narrowed it down to defining:
    var JSON = []; // @line 157
    If I take the ‘var’ off it works in IE.
    Please note I’m in IE 8, but I also tried compatibility mode.

  5. Jim Dalton

    I see, I assume “line 157″ refers to line 3 of the actual plugin code? Or is it someplace else in your application code?

    So I think I can guess at what is going on, which is that the variable JSON must already be defined in the scope somehow. If a variable is defined already within the scope, I believe it would throw an error if you tried to redeclare it with var. When you remove the var, you’re probably just setting the variable that has been already defined elsewhere.

    This was actually the *one* place in the code that I did touch, because in the original code for this function JSON was defined as a global variable. I added the var to give JSON local scope.

    Looking at it closer though, it appears that the conditional logic surrounding the declaration is probably no longer relevant….i.e. it should just say var JSON = {}; and the if (!this.JSON) condition can be safely removed.

    If it’s still not working after you do that, check the other JS you’re using. Are you declaring JSON elsewhere as a global variable? If so, maybe rename the global variable or give it local scope.

    Let me know the outcome…I think the plugin code should probably be amended assuming that works.

  6. geoff smith

    Having trouble with this library in the latest FireFox (3.5.2). The variable JSON is undefined. Anyone see this?

  7. Blackymetal

    The same issue reported by geoff smith,

    JSON is undefined
    if (typeof JSON.stringify !== ‘function’) {

  8. Robert Heessels

    Got it working in Firefox (3.5.x) by changing
    var JSON = {};
    into:
    this.JSON = {};

  9. Kevin Riley

    Just want to say thanks for posting this. Helps tremendously!

  10. Mathias

    I replaced the
    if (!this.JSON) {
    var JSON = {};
    }

    to
    if (!JSON) {
    var JSON = {};
    }

    and worked!

  11. {}

    this.JSON = {};

  12. Jeremy Ray Brown

    The following is a stringify method you can use for browsers that don’t support the JSON object (e.g. IE7):

    function Stringify(jsonData) {
    var strJsonData = ‘{‘;
    var itemCount = 0;
    for (var item in jsonData) {
    if (itemCount > 0) {
    strJsonData += ‘, ‘;
    }
    strJsonData += ‘”‘ + item + ‘”:”‘ + jsonData[item] + ‘”‘;
    itemCount++;
    }
    strJsonData += ‘}’;
    return strJsonData;
    }

  13. JavaScript和PHP中json object和json string互相转换 | Min的技术分享 – 54min.com

Post a comment

Contact Info
will not be published

include http://

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>