Three ways to convert JSON data into valid arrays

Source: Internet
Author: User
Tags arrays eval parse error

Includes global JSON objects and date Tojson methods.

1,eval Way of parsing, I am afraid this is the earliest analytic way.

View sourceprint?1 function Strtojson (str) {

2 var json = eval (' (' + str + ') ');

3 return JSON;

4}

Remember the parenthesis on both sides of the Str.

2,new function form, more bizarre Oh.

View sourceprint?1 function Strtojson (str) {

2 var json = (new function ("return" + str)) ();

3 return JSON;

4}

3, use the global JSON object.

View sourceprint?1 function Strtojson (str) {

2 return Json.parse (str);

9 ·

Currently IE8 (s)/FIREFOX3.5+/CHROME4/SAFARI4/OPERA10 has implemented this method.

The use of json.parse requires strict adherence to the JSON specification, such as a property that is enclosed in quotes, as follows

View sourceprint?1 var str = ' {name: ' Jack '} ';

2 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.