Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize javascript object to json and back

I am using to a jQuery post method to send some data to a server. Rather than constructing the JSON string myself, I would like to simply use a JavaScript object. When I get the return string (in JSON) I would like to automatically construct a corresponding JavaScript object.

Is this possible?

like image 920
rustybeanstalk Avatar asked Feb 15 '12 11:02

rustybeanstalk


2 Answers

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

Example:

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

var myJSONText = JSON.stringify(myObject, replacer); // js object to json string
like image 114
techfoobar Avatar answered Sep 29 '22 12:09

techfoobar


Yes.

If the JSON object is available, you can use :

var aString = JSON.stringify(anObject);

to transform an object into JSON string.

You can also convert a string into an object with

var obj = JSON.parse(aString)

To be sure that JSON is available, you can include this file https://github.com/douglascrockford/JSON-js

like image 37
j_freyre Avatar answered Sep 29 '22 13:09

j_freyre