Home > Web Front-end > JS Tutorial > Examples of two common methods for js to read json_javascript skills

Examples of two common methods for js to read json_javascript skills

WBOY
Release: 2016-05-16 16:33:31
Original
1303 people have browsed it

Method 1: The most famous eval method in js

Copy code The code is as follows:

var strJson="{name:'Zhang San'}";//json
var obj=eval("(" strJson ")");//Converted json object
alert(obj.name);//json name

Things to note about this method are:

The object expression {'name':'Zhang San'} must be expanded with "()", otherwise

Copy code The code is as follows:

var strJSON = "{name:'Zhang San'}";
var obj = eval(strJSON);
alert(obj.constructor);//String constructor
alert(obj.name);//undefine

The object expression must be expanded and eval executed to generate an anonymous object!

Method 2: Function construction definition method returns

Copy code The code is as follows:

var strJSON = "{name:'Zhang San'}";//The obtained JSON
var obj = new Function("return" strJSON)();//Converted JSON object
alert(obj.name);//json name
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template