如何解析html页面中的json数据

时间:2015-06-04 13:17:38

标签: javascript jquery html json

如何解析json数据,我需要在div元素中显示每个数据。我正在使用世界天气在线API服务来访问天气数据



<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
    <input type="text" id="in"></input>
    <input type="hidden" id="keys" value="api"></input>
    <input type="hidden" value="json" id="format"></input>
    <button id="go">Search</button>
   
    <script>
        $(document).ready(function(){
            $("#go").click(function(){
                var apikey = $("#keys").val();
                var q = $("#in").val();
                var format = $("#format").val();

                jQuery.ajax({
                    url: 'http://api.openweathermap.org/data/2.5/weather?key=' + apikey + '&q=' + q + '&format=' + format,
                    success: function(response) {
                        var obj = JSON.parse(response);
                        console.log(obj);
                    },
                });
            });
        });
    </script>
</body>
</html>
&#13;
&#13;
&#13;

柏林的示例输出:

http://api.openweathermap.org/data/2.5/weather?key=api&q=berlin&format=json

{"coord":{"lon":13.41,"lat":52.52},"sys":{"message":0.0826,"country":"DE","sunrise":1433386009,"sunset":1433445756},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01d"}],"base":"stations","main":{"temp":290.628,"temp_min":290.628,"temp_max":290.628,"pressure":1037.43,"sea_level":1043.19,"grnd_level":1037.43,"humidity":81},"wind":{"speed":2.42,"deg":314.504},"clouds":{"all":0},"dt":1433424243,"id":2950159,"name":"Berlin","cod":200}

1 个答案:

答案 0 :(得分:1)

在这里,JSON.parse(response)将返回一个数组。您可以通过键或索引访问数组中的元素。

例如,obj[0]是数组中的'0'th元素(或响应文本)'

obj.some_attribute_name将通过密钥访问该元素。