无法在Javascript中索引JSON对象

时间:2014-02-03 22:54:23

标签: javascript json jsonp

我能够传递整个JSON对象,但无法从中索引任何信息。

例如,以下代码将整个JSON字符串作为单个项目放在无序列表中

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Victoria Traffic</title>
</head>
<body>
    <div id="placeholder"></div>
        <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script>
    $.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://traffic.vicroads.vic.gov.au/maps.json') + '&callback=?', function(data){
        var output = "<ul>";
        output += data.contents;
        output += "</ul>";
        document.getElementById("placeholder").innerHTML = output;
  });
    </script>
</body>
</html>

但是以下代码不会输出控制台的任何内容:无法读取未定义的属性“0”。

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Victoria Traffic</title>
</head>
<body>
    <div id="placeholder"></div>
        <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script>
    $.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://traffic.vicroads.vic.gov.au/maps.json') + '&callback=?', function(data){
        var output = "<ul>";
        output += data.contents.incidents[0].id;
        output += "</ul>";
        document.getElementById("placeholder").innerHTML = output;
  });
    </script>
</body>
</html>

我做错了什么?

1 个答案:

答案 0 :(得分:1)

来自whateverorigin.org的响应似乎是JSON中包含的JSON:

{"contents": "{\"incidents\": ...}"}

虽然getJSON()将为您解析初始响应,但您必须自己解析内部值:

var contents = $.parseJSON(data.contents);

var output = "<ul>";
output += contents.incidents[0].id;
output += "</ul>";