Javascript如何解析JSON数组 [英] Javascript how to parse JSON array

查看:114
本文介绍了Javascript如何解析JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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.

我正在尝试像这样:

var jsonData = Ext.util.JSON.decode(myMessage);
for (var counter in jsonData.counters) {
     console.log(counter.counter_name);
 }

我做错了什么?
谢谢!

What am i doing wrong ? Thank you!

推荐答案

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");

与您的示例一起使用:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆