【问题标题】:Iterate through JSON response to get keys and values from array/object遍历 JSON 响应以从数组/对象中获取键和值
【发布时间】:2014-12-21 18:11:06
【问题描述】:

我正在尝试遍历行业标识符列表并保存类型和标识符值。

我已尝试使用以下代码,但输出未定义。

var url = "https://www.googleapis.com/books/v1/volumes/EXiMZwEACAAJ";
        $.getJSON(url, function(data) {
                var bookID = data.items[0].id;
                var title = data.items[0].volumeInfo.title;
                var industryIdentifiers = data.items[0].volumeInfo.industryIdentifiers;
                $.each(industryIdentifiers, function(result){
                    var idType = result.type;
                    var idValue = result.identifier;
                    alert (idType + " = " + idValue);
                });
        });

【问题讨论】:

  • 你能发布来自Google API的响应JSON吗?

标签: jquery json parsing iteration jsonobject


【解决方案1】:

这是因为你错误地使用了$.each,$.each 有如下回调结构,

回调

Type: Function( String propertyName, Object valueOfProperty )
The function that will be executed on every object.

所以,只需使用 ,

 $.each(industryIdentifiers, function(result){

将产生 result 作为 index 而不是您的寻找价值。从而为您提供undefined 值。

这是工作代码,

var url = "https://www.googleapis.com/books/v1/volumes/EXiMZwEACAAJ";
        $.getJSON(url, function(data) {
                var bookID = data.id;
                var title = data.volumeInfo.title;
                var industryIdentifiers =       data.volumeInfo.industryIdentifiers;
                $.each(industryIdentifiers, function(index,value){
                    var idType = value.type;
                    var idValue = value.identifier;
                    alert (idType + " = " + idValue);
                });
        });

而且,您可以查看demo here。

而且,您也错误地访问了结果 JSON。由于它返回单个值,您可以直接以data.id 访问它。

【讨论】:

    【解决方案2】:

    试试这个代码...

     $(document).ready( function() {
      var url = "https://www.googleapis.com/books/v1/volumes/EXiMZwEACAAJ";
            $.getJSON(url).done(function( data ){
                    var bookID = data.id;
                    var title = data.volumeInfo.title;
                    var industryIdentifiers = data.volumeInfo.industryIdentifiers;
                    //console.log(industryIdentifiers);
                    $.each(industryIdentifiers, function(i, item){
                        console.log(item);
                        var idType = item.type;
                        var idValue = item.identifier;
                        alert (idType + " = " + idValue);
                    });
            });
     });
    

    小提琴:http://jsfiddle.net/v5cornfb/

    【讨论】:

      【解决方案3】:

      你有两个问题。第一个问题是 data.items 未定义,要访问该数据对象中的属性,您必须执行此 data.nameOfProperty。您的第二个问题是,当您遍历行业标识符时,您必须在 $.each 调用中为匿名函数声明第二个参数。由于第一个参数只是数组的索引,而第二个参数是元素的值,在这种情况下,它将是具有类型和标识符属性的对象。

      【讨论】:

        猜你喜欢
        • 2017-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-07
        • 1970-01-01
        • 2014-10-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多