Javascript 如何解析 JSON 数组 [英] Javascript how to parse JSON array
问题描述
我正在使用 Sencha Touch (ExtJS) 从服务器获取 JSON 消息.我收到的消息是这样的:
I'm using Sencha Touch (ExtJS) to get a JSON message from the server. The message I receive is this one :
{
"success": true,
"counters": [
{
"counter_name": "dsd",
"counter_type": "sds",
"counter_unit": "sds"
},
{
"counter_name": "gdg",
"counter_type": "dfd",
"counter_unit": "ds"
},
{
"counter_name": "sdsData",
"counter_type": "sds",
"counter_unit": " dd "
},
{
"counter_name": "Stoc final",
"counter_type": "number ",
"counter_unit": "litri "
},
{
"counter_name": "Consum GPL",
"counter_type": "number ",
"counter_unit": "litri "
},
{
"counter_name": "sdg",
"counter_type": "dfg",
"counter_unit": "gfgd"
},
{
"counter_name": "dfgd",
"counter_type": "fgf",
"counter_unit": "liggtggggri "
},
{
"counter_name": "fgd",
"counter_type": "dfg",
"counter_unit": "kwfgf "
},
{
"counter_name": "dfg",
"counter_type": "dfg",
"counter_unit": "dg"
},
{
"counter_name": "gd",
"counter_type": "dfg",
"counter_unit": "dfg"
}
]
}
我的问题是我无法解析这个 JSON 对象,所以我可以使用每个计数器对象.
My problem is that I can't parse this JSON object so that i can use each of the counter objects.
我正在尝试像这样完成:
I'm trying to acomplish that like this :
var jsonData = Ext.util.JSON.decode(myMessage);
for (var counter in jsonData.counters) {
console.log(counter.counter_name);
}
我做错了什么?谢谢!
推荐答案
Javascript 有一个内置的字符串 JSON 解析,我认为这就是你所拥有的:
Javascript has a built in JSON parse for strings, which I think is what you have:
var myObject = JSON.parse("my json string");
在你的例子中使用它是:
to use this with your example would be:
var jsonData = JSON.parse(myMessage);
for (var i = 0; i < jsonData.counters.length; i++) {
var counter = jsonData.counters[i];
console.log(counter.counter_name);
}
编辑:您在使用 for 循环时有一个错误(我第一次阅读时错过了这一点,感谢@Evert).使用 for-in 循环会将 var 设置为当前循环的属性名称,而不是实际数据.请参阅上面我更新的循环以了解正确用法
EDIT: There is a mistake in your use of for loop (I missed this on my first read, credit to @Evert for the spot). using a for-in loop will set the var to be the property name of the current loop, not the actual data. See my updated loop above for correct usage
重要:JSON.parse
方法在旧的旧浏览器中不起作用 - 因此,如果您打算通过某种时间弯曲互联网连接使您的网站可用,这可能有问题!如果你真的有兴趣,这里是一个支持图表(我所有的方框都打勾).
IMPORTANT: the JSON.parse
method wont work in old old browsers - so if you plan to make your website available through some sort of time bending internet connection, this could be a problem! If you really are interested though, here is a support chart (which ticks all my boxes).
这篇关于Javascript 如何解析 JSON 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!