For example, I have two variables, I want to convert a to a string, convert B to a JSON object:
View Source print?
1 |
var a={"name": "Tom", "Sex": "Male", "Age": "24"}; |
2 |
var b= ' {' name ': ' Mike ', ' sex ': ' Female ', ' age ': ' 29 '} '; |
Advanced browsers such as FIREFOX,CHROME,OPERA,SAFARI,IE9,IE8 can directly use the stringify () and Parse () methods of the JSON object.
Json.stringify (obj) converts JSON to a string. Json.parse (String) converts a string to JSON format;
The above conversion can be written like this:
View Source print?
1 |
var a={"name": "Tom", "Sex": "Male", "Age": "24"}; |
2 |
var b= ' {' name ': ' Mike ', ' sex ': ' Female ', ' age ': ' 29 '} '; |
3 |
var atostr=json.stringify (a); |
4 |
var btoobj=json.parse (b); |
5 |
Alert (typeof (Atostr)); //string |
6 |
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 IE8 (compatibility mode), IE7 and IE6 can support JSON objects and their stringify () and parse () method, you can get this JS on the HTTPS://GITHUB.COM/DOUGLASCROCKFORD/JSON-JS, usually use Json2.js now.
IE8 (compatible mode), IE7 and IE6 can use eval () to convert a string to a JSON object.
View Source print?
1 |
var c= ' {' name ': ' Mike ', ' sex ': ' Female ', ' age ': ' 29 '} '; |
2 |
var ctoobj=eval ("(" +c+ ")"); |
3 |
Alert (typeof (Ctoobj)); |
JQuery also has a method Jquery.parsejson (JSON) that converts a string to JSON format, accepts a well-formed JSON string, and returns the parsed JavaScript (JSON) object. Of course, if you are interested in encapsulating a jQuery extension yourself, Jquery.stringifyjson (obj) converts JSON to a string.