weixin_33726313 2013-05-02 11:38 采纳率: 0%
浏览 908

如何获取json数据中对象数组的长度?

在我的应用程序中,我正在通过.aspx页面上的ajax调用获取Json数据。 json数据格式如下:

{
    "Table": [
        {
            "id": 911,
            "source": "Vishakhapatnam",
            "dest": "Goa",
            "capacity": 24000,
            "h1": 400,
            "h1At": 7,
            "h1Dt": 8,
            "h2": 401,
            "h2At": 9,
            "h2Dt": 9.3,
            "h3": 402,
            "h3At": 12,
            "h3Dt": 12.3,
            "h4": 403,
            "h4At": 14.3,
            "h4Dt": 15,
            "h5": 404,
            "h5At": 16,
            "h5Dt": 17,
            "h6": 405,
            "h6At": 18,
            "h6Dt": 19,
            "h7": 406,
            "h7At": 19.3,
            "h7Dt": 20,
            "h8": 407,
            "h8At": 21,
            "h8Dt": 21.3,
            "h9": 408,
            "h9At": 22,
            "h9Dt": 22.1,
            "h10": 409,
            "h10At": 23,
            "h10Dt": 24
        }
    ]
}

我在 http://jsonlint.com/ 的有效格式中对此格式进行了检查。

当我试图读取像这样的数据长度时,使用Javascript:

for (var i = 1; i <= data.Table.length; i++)

data.Table.length返回1且循环仅运行一次,我不知道如何获取json数据中对象数组的长度,以便循环可以持续到结束。

请帮帮我!

  • 写回答

2条回答 默认 最新

  • weixin_33736048 2013-05-02 11:43
    关注

    It's because your Table object contains an array with only one element. To get all objects you're looking for, try this instead:

    for (var i = 1; i <= data.Table[0].length; i++)
    

    Then your going inside the first element i Table and you'll get the number of children inside.

    Hope this helps!

    Edit

    Sorry, that's because objects don't have a length property. Please refer to this thread on StackOverflow, jQuery ajax json response has length undefined and incorrect data

    If you want to loop all objects try this,

    for (var obj in data.Table[0])
        console.log(obj) // Do something with your object
    
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么在stm32门禁成品上增加记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 解riccati方程组