Serialize javascript object to json and back

荒凉一梦 提交于 2019-12-09 00:41:26

问题


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?

Thanks in advance.


回答1:


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



回答2:


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




回答3:


you should use Douglas Crockford's JSON2 library.

That way, you could:

var jsonString = JSON.stringify(obj);

or

var Obj = JSON.parse(jsonString);



回答4:


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



来源:https://stackoverflow.com/questions/9292823/serialize-javascript-object-to-json-and-back

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!