我需要一些關於JavaScript的幫助。我做了一個ajax調用點擊按鈕,它返回下面的String,這是使用GSON生成的(基本上它是一個JSON對象)。如何將JSONString轉換爲Javascript對象
{
"chart":{
"renderTo":"container",
"type":"bar"
},
"title":{
"text":"Engagement Per Vendor Per GBP"
},
"subtitle":{
"text":"ASPT"
},
"xAxis":{
"categories":[
"A",
"B",
"C",
"D"
],
"title":{
"text":"Engagement Per Vendor Per GBP"
}
},
"yAxis":{
"min":0,
"title":{
"text":"Count",
"align":"high"
}
},
"plotOptions":{
"bar":{
"dataLabels":{
"enabled":true
}
}
},
"legend":{
"layout":"vertical",
"align":"right",
"verticalAlign":"bottom",
"x":-100,
"y":100,
"floating":true,
"borderWidth":1,
"backgroundColor":"#FFFFFF",
"shadow":true
},
"credits":{
"enabled":true
},
"series":[
{
"name":"ABC",
"data":[
10,
20,
20,
30
]
},
{
"name":"DEF",
"data":[
10,
20,
30,
40
]
},
{
"name":"GHIJ",
"data":[
20,
30,
40,
10
]
},
{
"name":"KLMN",
"data":[
10,
40,
20,
30
]
}
]
}
當我得到這些數據在我的JavaScript。 我試圖使用下面的語句
var jsonObj = eval(xmlHttp.responseText);
xmlHttp.responseText
將對象轉換爲JSON具有以下字符串
{"chart":{"renderTo":"container","type":"bar"},"title":{"text":"Engagement Per Vendor Per GBP"},"subtitle":{"text":"ASPT"},"xAxis":{"categories":["A","B","C","D"],"title":{"text":"Engagement Per Vendor Per GBP"}},"yAxis":{"min":0,"title":{"text":"Count","align":"high"}},"plotOptions":{"bar":{"dataLabels":{"enabled":true}}},"legend":{"layout":"vertical","align":"right","verticalAlign":"bottom","x":-100,"y":100,"floating":true,"borderWidth":1,"backgroundColor":"#FFFFFF","shadow":true},"credits":{"enabled":true},"series":[{"name":"ABC","data":[10,20,20,30]},{"name":"DEF","data":[10,20,30,40]},{"name":"GHIJ","data":[20,30,40,10]},{"name":"KLMN","data":[10,40,20,30]}]}
當我嘗試運行JSP,它停在var jsonObj = eval(xmlHttp.responseText);
在很多時候我已經完成了這個工作,但這次數據是不同的。 JSON字符串由GSON API的JSON方法創建。
除非我把它放入JSON對象中,否則我將無法做任何事情。任何對此的幫助都是可以理解的。
問候, Senny
+1提Crockford的腳本。 – 2012-03-28 09:13:40