2016-09-10 51 views
0

我有PHP json字符串。在JSON中解析字符串js函数作为js函数

{"formatter":"function(){ return '<b>' + this.series.xAxis.categories[this.point.x] + '<\/b> sold <br><b>' + this.point.value + '<\/b> items on <br><b>' + this.series.yAxis.categories[this.point.y] + '<\/b>'; }"} 

我可以将JSON到PHP STRING这样这个答案的帮助Stackoverflow Answer

{"formatter":function(){ return '<b>' + this.series.xAxis.categories[this.point.x] + '<\/b> sold <br><b>' + this.point.value + '<\/b> items on <br><b>' + this.series.yAxis.categories[this.point.y] + '<\/b>'; }} 

但是,当我尝试JSON解析成对象与

jQuery.parseJSON(variableContainingPHPJSONstring) 

我有错误,如这个。

未捕获的SyntaxError:意外的标记ü在JSON第14位的

这是我对这个工作是一个HIGHCHART的JSON。

I have this type of highchart config data coming from db=> php Array=> php json => js string => js object

我只有与功能部件问题在这里。 在工具提示:formatter

+0

JSON中不允许使用函数,所以显然解析失败。 – trincot

+2

第二个不再是JSON,而是一个JavaScript对象。你不能使用'jQuery.parse'解析。 –

+0

我知道它...但我想要一种方法来实现这个... @trincot –

回答

1

函数无效json。如果你希望它可用,你将不得不eval()该函数。我鼓励你找到一种避免这样做的方法,或者有一个工具提示函数接受一行数据或者其他东西,但是这里有一个使用eval()来基本实现你想要的工作示例。

var data = { 
    key1: "123", 
    key2: "junk", 
    formatter: "(function(){return 4;})" 
}; 

var formatter = eval(data.formatter); 

console.log(formatter());