Mutual conversion between JSON objects and strings __json

Source: Internet
Author: User
Tags string to json

For example, I have two variables, I want to convert a to a string, convert B to a JSON object:

View Source print?

1 var a={"name": "Tom", "Sex": "Male", "Age": "24"};
2 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 the JSON object.

Json.stringify (obj) converts JSON to a string. Json.parse (String) converts a string to JSON format;

The above conversion can be written like this:

View Source print?

1 var a={"name": "Tom", "Sex": "Male", "Age": "24"};
2 var b= ' {' name ': ' Mike ', ' sex ': ' Female ', ' age ': ' 29 '} ';
3 var atostr=json.stringify (a);
4 var btoobj=json.parse (b);
5 Alert (typeof (Atostr));  //string
6 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 IE8 (compatibility mode), IE7 and IE6 can support JSON objects and their stringify () and parse () method, you can get this JS on the HTTPS://GITHUB.COM/DOUGLASCROCKFORD/JSON-JS, usually use Json2.js now.

IE8 (compatible mode), IE7 and IE6 can use eval () to convert a string to a JSON object.

View Source print?

1 var c= ' {' name ': ' Mike ', ' sex ': ' Female ', ' age ': ' 29 '} ';
2 var ctoobj=eval ("(" +c+ ")");
3 Alert (typeof (Ctoobj));

JQuery also has a method Jquery.parsejson (JSON) that converts a string to JSON format, accepts a well-formed JSON string, and returns the parsed JavaScript (JSON) object. Of course, if you are interested in encapsulating a jQuery extension yourself, Jquery.stringifyjson (obj) converts JSON to a 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.