Conversion between string and json in js

Source: Internet
Author: User
Tags eval json

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.