For example, I have two variables, I want to convert a to a string and B to a JSON object:
var a={"name": "Tom", "Sex": "Male", "Age": "24″};
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 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:
var a={"name": "Tom", "Sex": "Male", "Age": "24″};
var b= ' {' name ': ' Mike ', ' sex ': ' Female ', ' age ': ' 29″} ';
var atostr=json.stringify (a);
var btoobj=json.parse (b);
Alert (typeof (Atostr)); String
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; Https://github.com/douglascrockford/JSON-js on Get to this JS, generally now with json2.js.
IE8 (compatibility mode), IE7 and IE6 can use eval () to convert a string to a JSON object.
var c= ' {' name ': ' Mike ', ' sex ': ' Female ', ' age ': ' 29″} ';
var ctoobj=eval ("(" +c+ ")");
Alert (typeof (Ctoobj));
jquery also has a way to convert strings to JSON format Jquery.parsejson (JSON) , 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