JS String Conversion to josn object

Source: Internet
Author: User

During Ajax development projects, strings in JSON format are often returned to the front end, and the front end is parsed into JS objects (JSON ).

 

ECMA-262 (E3)The JSON concept is not written to the standard.ECMA-262 (E5)The concept of JSON in is 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. As follows:

 

JS Code
    1. FunctionStrtojson (STR ){
    2. VaRJSON = eval ('('+ STR +')');
    3. ReturnJSON;
    4. }

 

Remember the parentheses on both sides of Str.

 

2. The new function format is weird. As follows:

 

JS Code
    1. FunctionStrtojson (STR ){
    2. VaRJSON = (NewFunction ("Return"+ Str ))();
    3. ReturnJSON;
    4. }

 

3. Use the global JSON object as follows:

 

JS Code
    1. FunctionStrtojson (STR ){
    2. ReturnJSON. parse (STR );
    3. }

 

At present, IE8 (s)/firefox3.5 +/chrome4/safari4/opera10 has implemented this method. The following are some materials:

 

Http://blogs.msdn.com/ie/archive/2008/09/10/native-json-in-ie8.aspx

Https://developer.mozilla.org/en/Using_JSON_in_Firefox

 

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

 

JS Code
    1. VaRSTR ='{Name: "Jack "}';
    2. VaROBJ = 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.

 

 

For details, see the special implementation of JSON. parse in chrome.

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.