1. 程式人生 > >json字串中,包含函式的處理

json字串中,包含函式的處理

json字串中,包含函式時,使用JSON.parse(strJSON)轉換時,定義的字串函式被識別成普通的字串。

比如:{"formate":"function test(){ return 1;}"}

可以使用JSON.parse(str,funReviver)中第二個引數funReviver 指定每個json物件,呼叫funReviver函式。

程式碼如下:

var str  =' {"formate":"function test(){ return 1;}"}';

var jsonObj = JSON.parse(str,funReviver);

function funReviver(key,value){
  
  if(key == 'formatter' &&  "string" == typeof  value && value.indexOf('function')== 0 ){
  //alert(key);
 return Function('return ' + value)();
  }
  return value;
}