Serializing to JSON in jQuery

910,743

Solution 1

I've been using jquery-json for 6 months and it works great. It's very simple to use:

var myObj = {foo: "bar", "baz": "wockaflockafliz"};
$.toJSON(myObj);

// Result: {"foo":"bar","baz":"wockaflockafliz"}

Solution 2

Works on IE8+

No need for jQuery, use:

JSON.stringify(countries); 

Solution 3

I haven't used it but you might want to try the jQuery plugin written by Mark Gibson

It adds the two functions: $.toJSON(value), $.parseJSON(json_str, [safe]).

Solution 4

No, the standard way to serialize to JSON is to use an existing JSON serialization library. If you don't wish to do this, then you're going to have to write your own serialization methods.

If you want guidance on how to do this, I'd suggest examining the source of some of the available libraries.

EDIT: I'm not going to come out and say that writing your own serliazation methods is bad, but you must consider that if it's important to your application to use well-formed JSON, then you have to weigh the overhead of "one more dependency" against the possibility that your custom methods may one day encounter a failure case that you hadn't anticipated. Whether that risk is acceptable is your call.

Solution 5

I did find this somewhere. Can't remember where though... probably on StackOverflow :)

$.fn.serializeObject = function(){
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
Share:
910,743
Herb Caudill
Author by

Herb Caudill

Herb is the founder and CTO of DevResults, a web app for managing foreign aid projects. DevResults is intended to make international development, grant-making, humanitarian assistance, and disaster relief programs more effective. It includes tools for monitoring & evaluation, mapping, project management, and collaboration.

Updated on April 20, 2020

Comments

  • Herb Caudill
    Herb Caudill about 4 years

    I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this?

    My specific situation: I have an array defined as shown below:

    var countries = new Array();
    countries[0] = 'ga';
    countries[1] = 'cd';
    ...
    

    and I need to turn this into a string to pass to $.ajax() like this:

    $.ajax({
        type: "POST",
        url: "Concessions.aspx/GetConcessions",
        data: "{'countries':['ga','cd']}",
    ...
    
  • Ryan Duffield
    Ryan Duffield over 15 years
    Writing your own JSON serialization method is bad. There, I said it. :-)
  • jamesmortensen
    jamesmortensen over 13 years
    Doing anything that someone else has already done is bad. Most of us are paid to get the job done, not reinvent wheels.
  • Marcello Nuccio
    Marcello Nuccio about 13 years
  • Jay Taylor
    Jay Taylor almost 13 years
    This doesn't actually serialize the object to a JSON string.
  • jamesmortensen
    jamesmortensen almost 13 years
    @pyrony - Go to a web form on a website, load in the Jquery code in the FB Console, and then run this: var data = "" + $.toJSON($('form').serializeObject());. data is now a JSON string. Afterwards, run this: alert(typeof data); It should alert "string". Then run this: alert(data);, you should see JSON text. Finally, go to jsonlint.com and paste in the JSON string. It should validate as Valid JSON. I'm not sure I understand what you mean as everything seems to point to this producing valid JSON. Thanks again.
  • Evan Plaice
    Evan Plaice about 12 years
    +1 If you're already using jQuery, this is the way to go. JSON-js is great as a standalone library but this plugin seamlessly integrates JSON.stringify and JSON.parse with jQuery. It's a win-win. IMHO, this should be the accepted answer.
  • Marnen Laibow-Koser
    Marnen Laibow-Koser almost 12 years
    Note that $.parseJSON is now in jQuery core.
  • ripper234
    ripper234 over 11 years
    @EvanPlaice - What do you mean 'seammless integrates'. What do I gain by using jquery-json over JSON-js ?
  • Evan Plaice
    Evan Plaice over 11 years
    @ripper234 I mean that it uses the native JSON.stringify/JSON.parse methods if they're available, if not it will fall back to it's own implementation. Basically, it's a polyfill for JSON serialization. The benefit is that you get client-side JSON serialization whether or not your user's browser supports it natively.
  • matewka
    matewka over 11 years
    I've been looking for a IE6 JSON.stringify replacement and this is the only one working so far. I mean, including json.js manually works great but makes conflicts with jQuery "$" namespace.
  • rubo77
    rubo77 over 10 years
    I get $.toJSON is not a function on my server, so I included <script src="http://www.x-non.com/json/jquery.json-2.4.min.js"> </script>
  • jamesmortensen
    jamesmortensen over 10 years
    @rubo77 - I don't recall exactly why I was using jquery-json. This was posted over 2-3/4 years ago, and I think it was still cool to try and support IE7 and IE6 back then, which didn't have a built-in JSON parser. You can actually replace $.toJSON with JSON.stringify and get the same result without external dependencies, assuming you're only supporting modern browsers. Hope this helps! :)
  • Matthew Flaschen
    Matthew Flaschen almost 10 years
    @EvanPlaice, jquery-json is not a polyfill. It is a library that uses native functionality if available. Rather, JSON-js (json2.js specifically) is a polyfill because it provides the same JSON object and API browsers provide, but does not clobber native functionality (which means modern browsers still get the high-performance native implementation).
  • DigitalDesignDj
    DigitalDesignDj over 8 years
    Look out, IE8 does not support serializeArray