Home > Web Front-end > JS Tutorial > Summary of several ways to parse string into json_javascript skills

Summary of several ways to parse string into json_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 18:16:35
Original
1450 people have browsed it

1. The older method:

Copy code The code is as follows:

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

2. More commonly used methods:
Copy code The code is as follows:

function strToJson(str){
return (new Function("return " str ))();
}

3. JSON object method not supported by IE67:
Copy code The code is as follows:

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

4. jQuery provides Method:
Copy code The code is as follows:

parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
data = jQuery.trim( data );
if ( /^[],: {}s]*$/.test(data.replace(/\(?:["\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
.replace(/"[^"\nr]*"|true|false|null|-?d (?:.d*)?(?:[eE][ -]?d )?/g, "]" )
.replace(/(?:^|:|,)(?:s*[) /g, "")) ) {
return window.JSON && window.JSON.parse ?
window.JSON.parse( data ) :
(new Function("return " data))();

} else {
jQuery.error( "Invalid JSON: " data );
}
},
Related labels:
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