By Herb Caudill


2008-10-10 15:29:56 8 Comments

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']}",
...

11 comments

@bruce 2016-03-24 03:50:13

Yes, you should JSON.stringify and JSON.parse your Json_PostData before calling $.ajax:

$.ajax({
        url:    post_http_site,  
        type: "POST",         
        data:   JSON.parse(JSON.stringify(Json_PostData)),       
        cache: false,
        error: function (xhr, ajaxOptions, thrownError) {
            alert(" write json item, Ajax error! " + xhr.status + " error =" + thrownError + " xhr.responseText = " + xhr.responseText );    
        },
        success: function (data) {
            alert("write json item, Ajax  OK");

        } 
});

@user18015 2009-05-26 19:22:40

JSON-js - JSON in JavaScript.

To convert an object to a string, use JSON.stringify:

var json_text = JSON.stringify(your_object, null, 2);

To convert a JSON string to object, use JSON.parse:

var your_object = JSON.parse(json_text);

It was recently recommended by John Resig:

...PLEASE start migrating your JSON-using applications over to Crockford's json2.js. It is fully compatible with the ECMAScript 5 specification and gracefully degrades if a native (faster!) implementation exists.

In fact, I just landed a change in jQuery yesterday that utilizes the JSON.parse method if it exists, now that it has been completely specified.

I tend to trust what he says on JavaScript matters :)

All modern browsers (and many older ones which aren't ancient) support the JSON object natively. The current version of Crockford's JSON library will only define JSON.stringify and JSON.parse if they're not already defined, leaving any browser native implementation intact.

@user18015 2011-02-17 20:32:37

Good point @Mark0978. Just by way of explanation, the arguments to JSON.stringify are explained here. I've not seen a good usecase for the second parameter yet, but the last parameter is quite useful: it indicates how many spaces to use to indent with when formatting the JSON string.

@xmedeko 2011-10-04 08:39:46

Check the issues before using this solution: [github.com/douglascrockford/JSON-js/pull/13] Maybe safer is tweak this code create some JSON2 object and use it regardless the JSON support in the browser.

@Courtney Christensen 2012-02-16 00:03:18

@pat, the 2nd, "replacer" arg is very useful for custom serialization of known objects. For example, I am serializing SVG elements using: JSON.stringify(obj, function(key, val) { if (val instanceof SVGSVGElement) {return val.xml || new XMLSerializer().serializeToString(val);} return val;})

@Chris 2012-09-12 15:43:20

Crockford's code wasn't playing nice with some more complex jQuery selectors. When I commented out the Object.prototype modifications at the bottom of the file, it worked as expected.

@Shital Shah 2013-12-07 07:56:48

I actually prefer JSON3. It has AMD/requireJS support plus it does not use eval which Crockform himself mentioned as "evil". github.com/bestiejs/json3

@Shrish Shrivastava 2015-06-29 13:21:03

It's basically 2 step process:

First, you need to stringify like this

var JSON_VAR = JSON.stringify(OBJECT_NAME, null, 2); 

After that, you need to convert the string to Object

var obj = JSON.parse(JSON_VAR);

@jherax 2015-04-11 05:50:05

The best way is to include the polyfill for JSON object.

But if you insist create a method for serializing an object to JSON notation (valid values for JSON) inside the jQuery namespace, you can do something like this:

Implementation

// This is a reference to JSON.stringify and provides a polyfill for old browsers.
// stringify serializes an object, array or primitive value and return it as JSON.
jQuery.stringify = (function ($) {
  var _PRIMITIVE, _OPEN, _CLOSE;
  if (window.JSON && typeof JSON.stringify === "function")
    return JSON.stringify;

  _PRIMITIVE = /string|number|boolean|null/;

  _OPEN = {
    object: "{",
    array: "["
  };

  _CLOSE = {
    object: "}",
    array: "]"
  };

  //actions to execute in each iteration
  function action(key, value) {
    var type = $.type(value),
      prop = "";

    //key is not an array index
    if (typeof key !== "number") {
      prop = '"' + key + '":';
    }
    if (type === "string") {
      prop += '"' + value + '"';
    } else if (_PRIMITIVE.test(type)) {
      prop += value;
    } else if (type === "array" || type === "object") {
      prop += toJson(value, type);
    } else return;
    this.push(prop);
  }

  //iterates over an object or array
  function each(obj, callback, thisArg) {
    for (var key in obj) {
      if (obj instanceof Array) key = +key;
      callback.call(thisArg, key, obj[key]);
    }
  }

  //generates the json
  function toJson(obj, type) {
    var items = [];
    each(obj, action, items);
    return _OPEN[type] + items.join(",") + _CLOSE[type];
  }

  //exported function that generates the json
  return function stringify(obj) {
    if (!arguments.length) return "";
    var type = $.type(obj);
    if (_PRIMITIVE.test(type))
      return (obj === null ? type : obj.toString());
    //obj is array or object
    return toJson(obj, type);
  }
}(jQuery));

Usage

var myObject = {
    "0": null,
    "total-items": 10,
    "undefined-prop": void(0),
    sorted: true,
    images: ["bg-menu.png", "bg-body.jpg", [1, 2]],
    position: { //nested object literal
        "x": 40,
        "y": 300,
        offset: [{ top: 23 }]
    },
    onChange: function() { return !0 },
    pattern: /^bg-.+\.(?:png|jpe?g)$/i
};

var json = jQuery.stringify(myObject);
console.log(json);

@Tim Burkhart 2014-06-18 15:49:43

One thing that the above solutions don't take into account is if you have an array of inputs but only one value was supplied.

For instance, if the back end expects an array of People, but in this particular case, you are just dealing with a single person. Then doing:

<input type="hidden" name="People" value="Joe" />

Then with the previous solutions, it would just map to something like:

{
    "People" : "Joe"
}

But it should really map to

{
    "People" : [ "Joe" ]
}

To fix that, the input should look like:

<input type="hidden" name="People[]" value="Joe" />

And you would use the following function (based off of other solutions, but extended a bit)

$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
    if (this.name.substr(-2) == "[]"){
        this.name = this.name.substr(0, this.name.length - 2);
        o[this.name] = [];
    }

    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;
};

@Tahir Akhtar 2008-10-10 15:35:52

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]).

@Tahir Akhtar 2008-10-13 08:07:58

In jQuery, most good stuff comes in form of plugins. By avoiding plugins you will be re-writing a lot of already written stuff.

@Marnen Laibow-Koser 2012-07-05 18:50:39

Note that $.parseJSON is now in jQuery core.

@Kain Haart 2009-12-01 21:44:16

If you don't want to use external libraries there is .toSource() native JavaScript method, but it's not perfectly cross-browser.

@jmort253 2011-01-02 07:57:40

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;
};

@Marcello Nuccio 2011-03-11 21:33:13

@Jay Taylor 2011-06-01 21:38:27

This doesn't actually serialize the object to a JSON string.

@jmort253 2011-06-02 01:51:56

@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.

@rubo77 2013-10-01 04:43:04

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>

@jmort253 2013-10-01 06:43:23

@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! :)

@DigitalDesignDj 2015-10-12 17:56:16

Look out, IE8 does not support serializeArray

@pestatije 2011-08-29 06:57:32

Works on IE8+

No need for jQuery, use:

JSON.stringify(countries); 

@Cory House 2012-01-15 02:28:36

-1 Won't work in older browsers that lack native JSON serialization.

@James Westgate 2012-01-19 08:45:53

@Cory - Just include JSON-js which hands off to the native implementation if found

@Cory House 2012-01-19 21:16:04

Yup, agreed James. I use the same. The -1 was because there's no warning in this answer that you have to use a library to get support for older browsers.

@weltraumpirat 2012-04-03 09:56:39

This won't work for all browsers: ---> Not compatible with IE 6,7

@weltraumpirat 2012-04-03 09:57:32

I've removed the previous edit and added it as a comment, because it was clearly meant to comment on the issue.

@ripper234 2012-04-17 10:32:00

@weltraumpirat - Well, I added it in another wording + link to caniuse (before reading your comment). I think it's an essential part of the answer.

@weltraumpirat 2012-04-17 10:43:38

@ripper234 It might be an essential part of the solution, but isn't it kind of the point on SO to let each user be the one to edit and/or add additional information to his/her own answer in order to improve it? OP will be notified when a comment is posted...

@ripper234 2012-04-17 16:02:20

@weltraumpirat - SO is a wiki. If an edit improves an answer, go ahead and make it, don't ask for permission (You should also comment to notify the owner).

@Evan Plaice 2012-04-20 21:38:42

Take a look at jquery-json. It uses JSON.stringify but provides a fallback method if it's not available. Here's the source code.google.com/p/jquery-json/source/browse/trunk/src/…

@Thomas Eding 2012-08-22 22:44:02

Who cares about IE < 8? I don't. If I had my way, I wouldn't even program a single bit of Javascript for any version of it either.

@Izkata 2013-01-26 05:19:37

@ThomasEding Sometimes there isn't a choice. We have an unnervingly large number of clients in China that will leave if we stop supporting IE6, for example. They are shrinking, but still exist.

@Thomas Eding 2013-01-26 05:48:34

@Izkata: I know. I just like bashing it for fun. For personal projects I wouldn't bother. But for actual work, I would do whatever my boss wants me to do.

@Jay Taylor 2011-06-01 21:40:58

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"}

@Evan Plaice 2012-04-20 08:39:04

+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.

@ripper234 2012-12-06 09:42:58

@EvanPlaice - What do you mean 'seammless integrates'. What do I gain by using jquery-json over JSON-js ?

@Evan Plaice 2012-12-07 16:04:18

@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 2013-01-19 02:07:30

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.

@Matthew Flaschen 2014-06-27 19:36:45

@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).

@Adam Bellaire 2008-10-10 15:47:13

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.

@Ryan Duffield 2008-10-10 16:00:45

Writing your own JSON serialization method is bad. There, I said it. :-)

@jmort253 2011-01-02 07:55:34

Doing anything that someone else has already done is bad. Most of us are paid to get the job done, not reinvent wheels.

@Paul Alexander 2012-10-13 18:29:03

I'm gonna have to agree with @Adam on this one. He's not advocating just rolling your own, but suggesting that you think about what dependencies you take on before just accepting it and "getting the job done". Any time you take a dependency you are relying on an uncommitted uninvolved third party that doesn't really care about your project. Some libraries are well documented, well supported with a healthy community surrounding them and can usually be safe to use. But it's in your and your client's interest to actually know this ahead of time.

Related Questions

Sponsored Content

56 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

65 Answered Questions

[SOLVED] How to check whether a checkbox is checked in jQuery?

49 Answered Questions

[SOLVED] Convert form data to JavaScript object with jQuery

36 Answered Questions

[SOLVED] What is the correct JSON content type?

51 Answered Questions

[SOLVED] Can comments be used in JSON?

  • 2008-10-28 20:39:03
  • Michael Gundlach
  • 2041384 View
  • 7134 Score
  • 51 Answer
  • Tags:   json comments

30 Answered Questions

[SOLVED] Is JavaScript a pass-by-reference or pass-by-value language?

6 Answered Questions

[SOLVED] Why does Google prepend while(1); to their JSON responses?

40 Answered Questions

[SOLVED] Setting "checked" for a checkbox with jQuery?

40 Answered Questions

[SOLVED] How do I format a Microsoft JSON date?

15 Answered Questions

[SOLVED] "Thinking in AngularJS" if I have a jQuery background?

Sponsored Content