2. Conversion between JSON objects and strings

For example, I have two variables, I want to convert a to a string and b to a JSON object:

1 var a={"name":"tom","sex":"男","age":"24"};
2   
3 var b='{"name":"Mike","sex":"女","age":"29"}';

In Firefox, chrome, opera, safari, ie9, ie8 and other advanced browsers, you can directly use the stringify() and parse() methods of JSON objects.

JSON.stringify(obj) converts JSON to string. JSON.parse(string) converts the string to JSON format;

The above transformation can be written as:

01 var a={"name":"tom","sex":"男","age":"24"};
02   
03 var b='{"name":"Mike","sex":"女","age":"29"}';
04   
05 var aToStr=JSON.stringify(a);
06   
07 var bToObj=JSON.parse(b);
08   
09 alert(typeof(aToStr));  //string
10   
11 alert(typeof(bToObj));//object

JSON.stringify()

ie8 (compatibility mode), ie7 and ie6 do not have JSON objects, but http://www.json.org/ provides a json.js, so that ie8 (compatibility mode), ie7 and ie6 can support JSON objects and their stringify( ) and parse() methods; you can get this js on https://github.com/douglascrockford/JSON-js , and generally use json2.js now.

ie8 (compatibility mode), ie7 and ie6 can use eval() to convert strings to JSON objects,

1 var c='{"name":"Mike","sex":"女","age":"29"}';
2 var cToObj=eval("("+c+")");
3 alert(typeof(cToObj));

 

jQuery also has the method jQuery.parseJSON( json ) to convert a string to JSON format , which accepts a standard format JSON string and returns the parsed JavaScript (JSON) object. Of course, if you are interested, you can encapsulate a jQuery extension yourself. jQuery.stringifyJSON(obj) converts JSON to string.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324821381&siteId=291194637