Conversion between JSON objects and strings

Source: Internet
Author: User
Tags string to json

For example, if I have two variables, I want to convert a to a string and convert 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, and ie8 can directly use the stringify () and parse () Methods of JSON objects.
JSON. stringify (obj) converts JSON into a string. JSON. parse (string) converts a string to JSON format;
The preceding conversions can be written as follows:

Var a = {"name": "tom", "sex": "male", "age": "24 "};

Var B = '{"name": "Mike", "sex": "female", "age": "29 "}';

Var aToStr = JSON. stringify ();

Var bToObj = JSON. parse (B );

Alert (typeof (aToStr); // string

Alert (typeof (bToObj); // object
JSON. stringify ()
Ie8 (compatible mode), ie7 and ie6 do not have JSON objects, but http://www.json.org/with A json.js, this example of ie8 (compatible mode), ie7 and ie6 can support JSON objects and their stringify () and parse () methods; you can.
Ie8 (compatible mode), ie7 and ie6 can use eval () to convert strings into JSON objects,

Var c = '{"name": "Mike", "sex": "female", "age": "29 "}';
Var cToObj = eval ("(" + c + ")");
Alert (typeof (cToObj ));

JQuery also provides the JSON format conversion method jQuery. parseJSON (json). It accepts a standard JSON string and returns the parsed JavaScript (JSON) object. If you are interested, you can encapsulate a jQuery extension. jQuery. stringifyJSON (obj) converts JSON into a string.

Source: http://www.css88.com/archives/3919

Related Article

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.