Three methods for parsing JSON data in JavaScript

Source: Internet
Author: User
This article mainly introduces three methods for parsing JSON data in JavaScript. This article describes the eval () method, newFunction method, JSON. parse () method and other three methods. For more information, see Overview

At present, the JSON format is becoming more and more important in web development. Especially in the Process of ajax development projects, it is often necessary to return json strings to the front-end, the front end is parsed into a JS object (JSON ).
The JSON concept in ECMA-262 (E3) was not written to the standard, and the JSON concept in ECMA-262 (E5) was formally introduced, including the Global JSON object and the toJSON method of Date.
Three methods for parsing JSON data

Eval () method

The most common method to parse JSON data is to use javascript's eval () method. The Code is as follows:

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


This method has performance and security issues and is not recommended.
New Function Method

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


JSON. parse () method
This method only supports IE8/Firefox3.5 +/Chrome4/Safari4/Opera10 or later versions. These browsers are close to W3C standards and the toJSON method is implemented by default.

function toJson(str){ return JSON.parse(str);}


Json2.js selects the native version when the browser supports JSON. parse native, And it is API compatible with ES5. When ES5 is not fully popularized, John Resig recommends json2.js to use APIs compatible with ES5, it can be smoothly transitioned to ES5 in the future-as long as an import is removed, it will be replaced.

For more information about the three methods for parsing JSON data in JavaScript, see the PHP Chinese website!

Related Article

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.