把json字符串转换为json对象,json字符串中包含js函数该如何处理?
1. 巧用json.parse的第二个参数
复制代码
1
2
3
4
5
6
7
8
9
10var strJson = '{"id" : 78, "formate" : "function test(){ return 23;}"}'; var jsonObj = JSON.parse(strJson, hello); function hello(key, value) { if (key == 'formatter' && "string" == typeof value && value.indexOf('function') == 0) { return Function('return ' + value)(); } return value; }
2. eval函数(存在安全问题, 慎用)
复制代码
1
2
3
4
5
6// 只转换 console.log("*01*", eval("(function yes(){return 321;})")); //ƒ yes(){return 321;} // 转换并调用 console.log("*02*", eval("(" + "function yes(){return 321;}" + "()" + ")")); //32
3. 巧用 Function
普通函数也是一个对象,Function是它的构造函数,Function接收一个字符串参数,表示函数体内容,这是几种创建函数的方式之一,
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16var s1 = 'function fn1(){return "陕西省西安市";}'; // 转化并调用 function myFun2(){ return Function('return ' + s1 + "()")(); } console.log(myFun2()); //陕西省西安市 // 只转换 function myFun3(){ return Function('return ' + s1)(); } console.log(myFun3()); //ƒ fn1(){return "陕西省西安市";} // let tempFunc = new Function('return '+s1); tempFunc()() //陕西省西安市
最后
以上就是妩媚香烟最近收集整理的关于如何解析json字符串中的函数的全部内容,更多相关如何解析json字符串中内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复