使用jQuery读取JSON数据 [英] Reading JSON data with jQuery

查看:75
本文介绍了使用jQuery读取JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON文件,当页面加载时,我必须从该文件读取数据.我怀疑JSON结构有问题. JSONLint显示它是有效的.因此,我必须使用错误的方法来访问它.

I have a JSON file and i have to read data from this file when the page loads. I suspect there is something wrong with my JSON Structure. JSONLint is showing that it is valid. So i must be using the wrong method to access it.

它基本上是一个对象数组(或者就是我的想法).

It is basically an array of objects (or that is what i think).

{"Listings":[
{"Listing1":
    {
        "agency_code":"BP",
        "property_code":"BON1",
        "Property_GUID":"6dded624",
        "FileNo /":"",
        "country":"AUSTRALIA",
        "state":"New South Wales",
        "subregion /":""
            }
        },
   {"Listing1":
    {
        "agency_code":"BPGA",
        "property_code":"BONNSTG4-Lot11",
        "Property_GUID":"6dded624-cde2-429a-81d4-bd6f91256345",
        "FileNo /":"",
        "country":"AUSTRALIA",
        "state":"New South Wales",
        "subregion /":""
            }
        }
    ]
}

我正在使用$ .ajax读取JSON.文件加载成功.现在,我该如何访问各个列表",以及如何衡量总共有多少个列表? 我尝试$ .each遍历数组,但是我的代码无法正常工作.

I am using the $.ajax to read the JSON. The file is loading successfully. Now how do i access the individual "listings" and how to measure how many Listings are present in total? I tried the $.each to loop through the array but my code is not working.

推荐答案

您有一个对象数组,但是该数组不是第一层,它存储在顶级Listings属性中.

You have an array of objects, but that array is not the first tier, it's stored in the top-level Listings property.

$.ajax({
    dataType : 'json',
    success  : function (response) {
        for (var i = 0, len = response.Listings.length; i < len; i++) {
            //You can now access individual properties like this:
            var agencyCode = response.Listings[i].Listing1.agency_code;
        }
    }
});

for循环的执行速度将比jQuery的.each()$.each()快: http://jsperf.com/jquery-each-vs-for-loops/2

This for loop will perform faster than jQuery's .each() or $.each(): http://jsperf.com/jquery-each-vs-for-loops/2

这是一个演示: http://jsfiddle.net/btHy5/1/

这篇关于使用jQuery读取JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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