In-depth analysis of the role of Json.parse (), json.stringify () and eval () _javascript skills

Source: Internet
Author: User
Tags opening and closing tags

"JSON (JavaScript Object notation) is a lightweight format for data interchange. It is based on a subset of ECMAScript. Because of its language-independent text format and the use of a family of C-languages, these features make JSON an ideal data-exchange language, making it easy for people to read and write, as well as for machine parsing and generation (typically used to increase network transmission rates). ”

Here today I would like to talk about the Json.parse () and json.stringify () functions in jquery, incidentally, and mention the Eval () function in native JS.

(1) Json.parse function

Function: Converts a JavaScript object representation (JSON) string to an object.

Syntax: Json.parse (text [, Reviver])

Parameters:

Text required. A valid JSON string.

Reviver Optional. A function that converts the result. This function will be called for each member of the object.
Return value: An object or array

Example

var json = ' {' name ': ' GDT ', ' age ':, ' University ': ' Gdut '} ';
var info = json.parse (JSON); Resolves to JSON object
document.write (Info.name + ' is a student of ' + info.) University + ' and he ' + Info.age + "years old."); /info As Object

(2) json.stringify () function

Role: Converts JavaScript values to JavaScript Object representation (JSON) strings

Syntax: json.stringify (value [, Replacer] [, space])

Parameters:

Value required, usually a JavaScript value (usually an object or array) that needs to be converted

Replacer optional, function or array for converting results

Space is optional. Add indents, spaces, and line breaks to the return value JSON text to make it easier to read.

Return value: A string containing JSON text

Example

var info = {Name: "GDT", age:,university: "Gdut"};
var json = json.stringify (info); Convert to JSON string
document.write (JSON);//output to {"name": "GDT", "Age":, "University": "Gdut"}

(3) eval () function

Function: the eval () function computes a string and executes the JavaScript code in it.

Syntax: eval (String)

Parameters:

string required, the string to evaluate, which contains the JAVASCRIPT expression to evaluate or the statement to execute.

Return value: Returns the value of the computed string, if any (no changes are made to return)

Example

Eval ("x=;y=;d ocument.write (x*y)");  Output is
document.write (eval ("+")); Output is
var x=;
document.write (eval (x+)); Output is

Using the eval () function can also parse a JSON string into an object, which completes the function of Json.parse (), but there are different places, see the following code

Json.parse ()
var json = ' {' name ': ' GDT ', ' age ':, ' University ': ' Gdut '} ';
var info = json.parse (JSON); Resolves to JSON object
document.write (info),//output to [object]
//eval ()
var json = ' {' name ': ' GDT ', ' age ':, ' University ":" Gdut "}";
var info = eval (' (' + JSON + ') '); Parse to JSON object
document.write (info);//output to [object]

I don't know if you have any wood. Notice that eval () also packs the strings with a pair of parentheses, and I find a better explanation for this:

Cause: Due to the problem with Eval itself, because JSON starts and ends with "{}", in JS it is treated as a block of statements, so it must be coerced into an expression.

Workaround: The purpose of parentheses is to force the Eval function to force an expression in parentheses (expression) into an object when processing JavaScript code instead of executing as a statement (statement). For example, an object literal {}, if the outer bracket is not added, Eval recognizes the curly braces as the opening and closing tags of the JavaScript code block, then {} will be considered to have executed an empty statement. Please see the following examples of different

Alert (eval ("{}")); return undefined

In addition, eval () can parse any string relative to the strict Json.parse (), and eval is unsafe because eval is looser and has potential security implications. For example, the following code:

var str = ' {' A ': ' B '} ';
document.write (eval ("+str+")); Normal parsing to object
var str = ' {' A ': (function () {alert ("I can do something bad!");}) ()}';

If you inject a script with a malicious user in the JSON string to insert a Trojan link into the page, you can use eval as well, but with json.parse () you don't have to worry about the problem, and while the Eval () is powerful, the actual opportunity is not much.

Personal summary of the time, this is the first blog of my Life, in April 1 fool ' Day was born, write a bad place also hope you forgive me, now the technology is very slag, I very much hope that now can be a bit to accumulate knowledge, for the success of the future lay a good foundation, fighting~

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.