Converting between JSON objects and strings

Source: Internet
Author: User


For example, there are two variables, I want to convert a to a string and 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,IE8 can directly use the stringify () and Parse () methods of JSON objects.
Json.stringify (obj) converts the JSON to a string. Json.parse (String) to convert the string to JSON format;
The above conversions can be written like this:

var a={"name": "Tom", "Sex": "Male", "Age": "24"};

var b= ' {' name ': ' Mike ', ' sex ': ' Female ', ' age ': ' 29 '} ';

var atostr=json.stringify (a);

var btoobj=json.parse (b);

Alert (typeof (Atostr)); String

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 that IE8 (compatibility mode), IE7 and IE6 can support JSON objects and their stringify () and the Parse () method; You can get this JS on Https://github.com/douglascrockford/JSON-js, which is usually used json2.js.
IE8 (compatibility mode), IE7 and IE6 can use eval () to convert a string to a JSON object.

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

jquery also has a method Jquery.parsejson (JSON) that converts a string into JSON format, accepts a JSON string in a standard format, and returns the parsed JavaScript (JSON) object. Of course, if you are interested in encapsulating a jQuery extension yourself, Jquery.stringifyjson (obj) converts the JSON to a string.

Converting between JSON objects and strings

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.