Three ways to convert a string into JSON in JS

Source: Internet
Author: User
Tags parse error

ECMA-262 (E3) did not write the JSON concept to the standard, fortunately the concept of JSON in ECMA-262 (E5) was formally introduced, including the global JSON object and the Tojson method of date.

1,eval way to parse, I am afraid this is the earliest way to parse. As follows:

Copy CodeThe code is as follows:
function Strtojson (str) {
var json = eval (' (' + str + ') ');
return JSON;
}


Remember to do not forget the parentheses on both sides of Str.
2,new function form, more strange oh. As follows

Copy CodeThe code is as follows:
function Strtojson (str) {
var json = (new Function ("return" + str));
return JSON;
}


3, use the global JSON object, as follows:

Copy CodeThe code is as follows:
function Strtojson (str) {
return Json.parse (str);
}


At present IE8 (S)/FIREFOX3.5+/CHROME4/SAFARI4/OPERA10 has implemented the method, the following is part of the information: http://blogs.msdn.com/ie/archive/2008/09/10/ Native-json-in-ie8.aspx Https://developer.mozilla.org/en/Using_JSON_in_Firefox
Use Json.parse strict adherence to the JSON specification, such as attributes are required in quotation marks, as follows

Copy CodeThe code is as follows:
var str = ' {name: ' Jack '} ';
var obj = json.parse (str); --Parse Error


The name is not enclosed in quotation marks, and the parsing fails with the exception thrown in all browsers using Json.parse. And the first two ways are fine.
See also: Special implementations of Json.parse in Chrome

Three ways to convert a string into JSON in JS

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.