In data transmission, json is transmitted in the form of text, that is, a string, which is like a Json object: var str1 = '{"name": "Amy", "sex ": "woman"} '; console. log (typeof str1); the experimental type is string;
In actual projects, if you want to obtain the name and sex values, you need to use a Json object through str1.name and str1.sex, in this way, the string type must be converted to a Json object.
I. Method for converting string type to Json object
1. Conversion supported by Javascript: eval
Eval ('+ jsonstr + ')');
Note: enclose a pair of parentheses outside the json characters, ie8 (compatible mode), ie7 and ie6. You can also convert strings into JSON objects using eval (), but these methods are not recommended; the disadvantage is that it is not safe. eval executes the expression in the json string.
IT sharing
2. Browsers support conversion methods (Firefox, chrome, opera, safari, ie9, ie8) and other browsers:
JSON. parse (jsonstr); // you can convert a json string to a json object.
IT sharing
On the contrary, the browser provides a method to convert a Json object to a string type:
JSON. stringify (jsonstr); // converts a json object to a json string.
3. Conversion supported by jQuery plug-in:
$. ParseJSON (jsonstr); // jQuery. parseJSON (jsonstr), which can convert a json string to a json object
4. Official JSON conversion method:
Http://www.json.org/with a json.js, this IE8 (compatible mode), ie7 and ie6 can support the JSON object and its stringify () and parse () methods;
You can.
II. Method for converting a Json object to a String
The conversion method supported by the browser mentioned above is JSON. stringify (str ):
JSON. stringify (jsonstr); // converts a json object to a json string.