HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Serializing to JSON in jQuery

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
serializingjqueryjson

Problem

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

Solution

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.

Code Snippets

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

Context

Stack Overflow Q#191881, score: 1160

Revisions (0)

No revisions yet.