This question already has an answer here:
- Serializing an object to JSON 3 answers
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']}",
...
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.
It's basically 2 step process:
First, you need to stringify like this
After that, you need to convert the string to Object
Yes, you should JSON.stringify and JSON.parse your "Json_PostData" before calling $.ajax
I've been using jquery-json for 6 months and it works great. It's very simple to use:
If you don't want to use external libraries there is
.toSource()
native JavaScript method, but it's not perfectly cross-browser.JSON-js - JSON in JavaScript.
To convert an object to a string, use
JSON.stringify
:To convert a JSON string to object, use
JSON.parse
:It was recently recommended by John Resig:
I tend to trust what he says on JavaScript matters :)
Newer browsers support the JSON object natively. The current version of Crockford's JSON library will only define
JSON.stringify
andJSON.parse
if they're not already defined, leaving any browser native implementation intact.