Three ways to convert strings into JSON in JS __js

Source: Internet
Author: User
Tags parse error
In the development project using AJAX, it is often necessary to return the JSON-formatted string to the front end and parse the front end into a JS object (JSON).

ECMA-262 (E3) did not write the JSON concept into the standard, but fortunately in ECMA-262 (E5) The concept of JSON was formally introduced, including global JSON objects and date Tojson methods.

1,eval Way of parsing, I am afraid this is the earliest analytic way. As follows:
Copy code code as follows:

function Strtojson (str) {
var json = eval (' (' + str + ') ');
return JSON;
}

Remember to keep the parentheses on both sides of the Str.
2,new function form, more bizarre Oh. As follows
Copy code code as follows:

function Strtojson (str) {
var json = (new Function ("return" + str)) ();
return JSON;
}

3, use the global JSON object as follows:
Copy code code as follows:

function Strtojson (str) {
return Json.parse (str);
}

Currently IE8 (S)/FIREFOX3.5+/CHROME4/SAFARI4/OPERA10 has implemented the method, and the following are some of the data: http://blogs.msdn.com/ie/archive/2008/09/10/ Native-json-in-ie8.aspx Https://developer.mozilla.org/en/Using_JSON_in_Firefox
The use of json.parse requires strict adherence to the JSON specification, such as a property that is enclosed in quotes, as follows
Copy code code as follows:

var str = ' {name: ' Jack '} ';
var obj = json.parse (str); --> Parse Error

Name is not enclosed in quotation marks, and parsing fails with the exception being thrown in all browsers using Json.parse. The first two ways are fine.

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.