如何使用if语句循环遍历JSON对象?

时间:2011-11-04 05:29:28

标签: javascript jquery ajax json

这是JSON对象:

{
    "temperatures": {
        "city": [{
            "name": "Riyadh",
            "high": [35, 38, 32]
        }, {
            "name": "New York",
            "high": [28, 36]
        }, {
            "name": "Dubai",
            "high": [18, 20]
        }]
    }
}

在页面加载时,我通过AJAX获取对象。我需要遍历每个城市并获取城市名称和high数组。

这是页面代码:

<html>

    <head>
        <title>the title</title>

        <script type="text/javascript" src="tempj.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {

            $.getJSON('temp.json', function(data) {
                alert('<ul><li>'+ jd.city.name +':'  + jd.high + '</ul> ');
            });
        });
        </script>

    </head>

    <body>
    </body>

</html>

3 个答案:

答案 0 :(得分:3)

我不知道你在使用if语句的问题标题中的意思,所以我忽略了这一点。

在你的JSON中,data.temperatures.city是一个对象数组,每个对象都有两个属性,一个用于城市名称,另一个用于高位数组。我不知道你想如何处理highs数组有不同长度的事实,所以我只是使用.join()方法将它们形成一个逗号分隔的字符串,在警告的结尾处

据推测,你真的不想弹出一堆警报,但至少这是一个开始的地方,你可以看到你得到了你期望的数据,所以以下内容足以让你前进:

$.getJSON('temp.json', function(data) {
   for (var i = 0; i < data.temperatures.city.length; i++) {
      alert("The temperatures in " + data.temperatures.city[i].name + " are "
            + data.temperatures.city[i].high.join(","));
   }
});

我故意没有使用$.each(),所以出于学习目的,你可以看到发生了什么。显然,如果您愿意,可以将其转换为使用$.each()

您应该添加错误检查,确认您尝试使用的属性确实存在(即,JSON是预期的格式)。

答案 1 :(得分:1)

您可以访问数据以进入城市数组,然后遍历城市数组以获取该数组中每个元素的属性,如下所示:

var data = {
    "temperatures": {
        "city": [{
            "name": "Riyadh",
            "high": [35, 38, 32]
        }, {
            "name": "New York",
            "high": [28, 36]
        }, {
            "name": "Dubai",
            "high": [18, 20]
        }]
    }
}

var cityArray = data.temperatures.city;
for (var i = 0; i < cityArray.length; i++) {
    // cityArray[i].name   (name of city)
    // cityArray[i].high   (array of high values for that city)
}

答案 2 :(得分:0)

如果你使用jQuery,你可以循环遍历json元素

jQuery.getJSON('js/jsonTest.js',function(data) {
    $.each(data, function(key, val) {
        if (key == 'general') { 
            // code here
        } 
     }
}