views:

3245

answers:

3

Apparently jQuery has the ability to decode a given object or string into a JSON object. However, I have a JS object that I need to POST back to the server and I find no utility in jQuery that wraps the JSON.stringify() function. That function is found in Chrome, Safari 4, FF3.6, and IE8 but is not found in earlier browsers. I can use it natively in the browsers that support it, but otherwise am forced to fall back to using Crockford's JSON scripts.

Is there some built-in with jQuery that handles JSON encoding and decoding that takes the place of the Crockford scripts?

+3  A: 

You might want to check this out: http://www.json.org/js.html

shinkou
Yeah, its kind of sad that jQuery hasn't added a method to do this directly to the library. I ended up minifying json.js with Closure compiler and stuck it in the bottom of my js file where I'm working. It'll do the trick, but seems unnecessary.
Geuis
+1  A: 

jQuery can decode JSON strings natively with jQuery.parseJSON().

For encoding though, i only know of a plugin : jquery-json

Gaby
what's wrong with using JSON.stringify directly?
zcrar70
@zcrar70, he specifically asks for a `JSON.stringify` wrapper.. unless your comment is intended for the OP.
Gaby
A: 

You can use "Closure Library" (Google) to make a cross browser JSON encoder/decoder.

Just go to http://closure-compiler.appspot.com/

and insert the following into the text field, then hit "Compile":

// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @use_closure_library true
// ==/ClosureCompiler==

// ADD YOUR CODE HERE
goog.require('goog.json');
if (!window['JSON']) window['JSON']={};
if (typeof window['JSON']['serialize'] !== 'function') window['JSON']['serialize']=goog.json.serialize;
if (typeof window['JSON']['parse'] !== 'function') window['JSON']['parse']=goog.json.parse;
Stewe