Source: The conversion between a JSON object and a string
For example, I have two variables, I want to convert a to a string and B to a JSON object:
View SourcePrint?
1 |
vara={"name":"tom","sex":"男","age":"24"}; |
3 |
varb=‘{"name":"Mike","sex":"女","age":"29"}‘; |
Advanced browsers such as FIREFOX,CHROME,OPERA,SAFARI,IE9,IE8 can directly use the stringify () and Parse () methods of JSON objects.
Json.stringify (obj) converts the JSON to a string. Json.parse (String) to convert the string to JSON format;
The above conversions can be written like this:
View SourcePrint?
01 |
vara={"name":"tom","sex":"男","age":"24"}; |
03 |
varb=‘{"name":"Mike","sex":"女","age":"29"}‘; |
05 |
varaToStr=JSON.stringify(a); |
07 |
varbToObj=JSON.parse(b); |
09 |
alert(typeof(aToStr)); //string |
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 the Parse () method; You can get this JS on Https://github.com/douglascrockford/JSON-js, which is usually used json2.js.
IE8 (compatibility mode), IE7 and IE6 can use eval () to convert a string to a JSON object.
1 |
varc=‘{"name":"Mike","sex":"女","age":"29"}‘; |
2 |
varcToObj=eval("("+c+")"); |
jquery also has a method Jquery.parsejson (JSON) that converts a string into JSON format, accepts a JSON string in a standard format, and returns the parsed JavaScript (JSON) object. Of course, if you are interested in encapsulating a jQuery extension yourself, Jquery.stringifyjson (obj) converts the JSON to a string.
Converting between JSON objects and strings