How to convert a json string to a json object in js-javascript tips-js tutorial

Source: Internet
Author: User
Converts a json string to a json object. During data transmission, json is transmitted in the form of text, that is, strings, while JS operates on JSON objects. Therefore, mutual conversion between JSON objects and JSON strings is critical. For example:

JSON string:
Var str1 = '{"name": "cxh", "sex": "man "}';
JSON object:
Var str2 = {"name": "cxh", "sex": "man "};

1. convert a JSON string to a JSON object

To use str1 above, you must use the following method to first convert it to a JSON object:

// Converts a JSON string to a JSON object

Var obj = eval ('+ str + ')');

Or

Var obj = str. parseJSON (); // converts a JSON string to a JSON object.

Or

Var obj = JSON. parse (str); // converts a JSON string to a JSON object.

Then, you can read:

Alert (obj. name );

Alert (obj. sex );

NOTE: If obj is a JSON object, it is still a JSON object after eval () function conversion (even Multiple conversions), but parseJSON () is used () A problem occurs after the function is processed (a syntax exception is thrown ).

2. You can use toJSONString () or the global method JSON. stringify () to convert a JSON object to a JSON string.

For example:

Var last = obj. toJSONString (); // converts a JSON object to a JSON character

Or

Var last = JSON. stringify (obj); // converts a JSON object to a JSON character

Alert (last );

Note:

Among the methods above, except that the eval () function is provided by js, several other methods are from the json. js package. The new JSON version modifies the API and changes JSON. stringify () and JSON. both parse () methods are injected into the built-in Javascript Object, and the former becomes the Object. toJSONString (), and the latter is a String. parseJSON (). If you cannot find the toJSONString () and parseJSON () methods, the version of your json package is too low.

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.