Skip to content

Instantly share code, notes, and snippets.

@pzzrudlf
Last active November 4, 2015 02:33
Show Gist options
  • Save pzzrudlf/d504980e666768a20f09 to your computer and use it in GitHub Desktop.
Save pzzrudlf/d504980e666768a20f09 to your computer and use it in GitHub Desktop.
/**
* THE FIRST METHOD OF CONVERTING STRING TO JSON OBJECT
*
*/
function strToJson(str){
var json = eval('(' + str + ')');
return json;
}
/**
* THE SECOND METHOD OF CONVERTING STRING TO JSON OBJECT
*
*/
function strToJson(str){
var json = (new Function("return " + str))();
return json;
}
/**
* THE THIRD METHOD OF CONVERTING STRING TO GLOBAL JSON OBJECT
*
*/
function strToJson(str){
return JSON.parse(str);
}
/**
* 使用JSON.parse需严格遵守JSON规范,如属性都需用引号引起来,如下
*
* var str = '{name:"jack"}';
* var obj = JSON.parse(str); // --> parse error
* name没有用引号引起来,使用JSON.parse所有浏览器中均抛异常,解析失败。而前两种方式则没问题
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment