2016-09-10 52 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());