Serialize javascript object for json and back

I use the jQuery post method to send some data to the server. Instead of creating a JSON string myself, I would just like to use a Javascript object. When I get the return string (in JSON), I would like to automatically create the corresponding javascript object. Is it possible?

Thanks in advance.

+5
source share
4 answers

Checkout JSON.stringify()and JSON.parse()in the documentation JSON2

Example:

myData = JSON.parse(text); // from json string to js object

var myJSONText = JSON.stringify(myObject, replacer); // js object to json string
+20
source

Yes.

If a JSON object is available, you can use:

var aString = JSON.stringify(anObject);

to convert an object to a JSON string.

You can also convert a string to an object using

var obj = JSON.parse(aString)

, JSON , https://github.com/douglascrockford/JSON-js

+6

you should use the Douglas Crockford JSON2 library .

So you could:

var jsonString = JSON.stringify(obj);

or

var Obj = JSON.parse(jsonString);
+2
source

If you use jQuery.getJSON you don't have to worry about json string and parsing, jquery does it for you.

+1
source

All Articles