Three methods for converting strings to JSON

Source: Internet
Author: User
Tags parse error

During Ajax project development, strings in JSON format are often returned to the front end, and the front end is parsed into JS objects (JSON ).
The JSON concept was not written to the standard in ECMA-262 (E3), but in ECMA-262 (E5) The JSON concept was formally introduced, including the Global JSON object and the tojson method of date.

1. Eval parsing. I'm afraid this is the earliest parsing method.

View sourceprint?
1 Function Strtojson (STR ){
2 VaR JSON = eval ('(' + STR +')');
3 Return JSON;
4 }

Remember the parentheses on both sides of Str.

2. The new function format is weird.

View sourceprint?
1 Function Strtojson (STR ){
2 VaR JSON = (New Function ("Return" + Str ))();
3 Return JSON;
4 }

3. Use a global JSON object.

View sourceprint?
1 Function Strtojson (STR ){
2 Return JSON. parse (STR );
3 }

Currently, IE8 (s)/firefox3.5 +/chrome4/safari4/opera10 has implemented this method.

JSON. parse must comply with JSON specifications strictly. If attributes are enclosed by quotation marks

View sourceprint?
1 VaR STR ='{Name: "Jack "}';
2 VaR OBJ = JSON. parse (STR );// --> Parse error

Name is not enclosed in quotation marks. If JSON. parse is used, an exception is thrown in all browsers and parsing fails. The first two methods 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.