javascript解析从服务器返回的json格式数据

时间:2024-05-28 13:03:50

在javascript中我们可以将服务器返回的json格式数据转换成json格式进行使用,如下:

1、服务器返回的json格式数据:

通过response.responseText获得:

"{"datas":[{"qianyypHaoml":{"gaokgl":"0.0","mein":"0.0","dikgl":"0.0","gaokdl":"0.0","dikdl":"0.0","liez":"0.0","hem":"11.0"},"qianyepHaoml":{"gaokgl":"0.0","mein":"0.0","dikgl":"0.0","gaokdl":"0.0","dikdl":"0.0","liez":"44.0","hem":"0.0"},"houyypHaoml":{"gaokgl":"0.0","mein":"0.0","dikgl":"0.0","gaokdl":"0.0","dikdl":"55.0","liez":"0.0","hem":"0.0"},"houyepHaoml":{"gaokgl":"0.0","mein":"44.0","dikgl":"0.0","gaokdl":"0.0","dikdl":"0.0","liez":"0.0","hem":"0.0"},"baibypHaoml":{"gaokgl":"99.0","mein":"0.0","dikgl":"0.0","gaokdl":"0.0","dikdl":"0.0","liez":"0.0","hem":"0.0"},"baibepHaoml":{"gaokgl":"33.0","mein":"0.0","dikgl":"0.0","gaokdl":"0.0","dikdl":"0.0","liez":"0.0","hem":"0.0"},"qianyHaomzl":{"gaokgl":"0.0","mein":"0.0","dikgl":"0.0","gaokdl":"0.0","dikdl":"0.0","liez":"44.0","hem":"11.0"},"houyHaomzl":{"gaokgl":"0.0","mein":"44.0","dikgl":"0.0","gaokdl":"0.0","dikdl":"55.0","liez":"0.0","hem":"0.0"},"baibHaomzl":{"gaokgl":"132.0","mein":"0.0","dikgl":"0.0","gaokdl":"0.0","dikdl":"0.0","liez":"0.0","hem":"0.0"},"quantHaomzl":{"quantHaomzl":"286.0"},"quantGaokglHaoml":{"gaokgl":"132.0"},"quantGaokdlHaoml":{"gaokdl":"0.0"},"quantDikglHaoml":{"dikgl":"0.0"},"quantDikdlHaoml":{"dikdl":"55.0"},"quantLiezHaoml":{"liez":"44.0"},"quantMeinHaoml":{"mein":"44.0"},"quantHemHaoml":{"hem":"11.0"},"quantDilHaoml":{"dil":"55.0"},"quantGaolHaoml":{"gaol":"132.0"}}]}"

2、上面是获得的一个json对象,通过eval方法将上面的数据转换成json格式

var result = eval("(" + response.responseText.replace(/\"/g, "'") + ")");

replace方法是将上面数据的所有双引号全部转换成单引号,具体/g的含义看这篇文章:http://www.cnblogs.com/smallrock/p/3489597.html

/g是将所有的双引号全部替换成单引号。

3、转换成json格式后可以通过对象的方式进行访问,既通过“.”的方式

if(result.datas.length == 0 || result.datas.length == '0')
{
Ext.Msg.alert('提示信息', '没有记录返回!');
return;
}
else
{
alert(result.datas[0].qianyypHaoml.gaokgl);
}