【问题标题】:Parse Json in javascript for keys contains backslash在 javascript 中为键解析 Json 包含反斜杠
【发布时间】:2013-11-28 11:10:03
【问题描述】:

我正在尝试在 jQuery 中解析以下 freebase API。

https://www.googleapis.com/freebase/v1/search?query=us%20president&filter=(all%20type:/people/person)&output=(/common/topic/image)

但是当我尝试访问 /common/topic/image "mId" for image 时遇到问题。

谁能告诉我什么是访问包含"/common/topic/image"这些类型键的对象或数组的正确方法。

谢谢!

【问题讨论】:

    标签: javascript jquery json


    【解决方案1】:
    $.getJSON("https://www.googleapis.com/freebase/v1/search?query=us%20president&filter=(all%20type:/people/person)&output=(/common/topic/image)", function (data) {
        var r = data.result; 
        // iterate each result   
        $.each(r, function (i, j) {
            var arr = j.output['/common/topic/image'];
            //iterate each arr['/common/topic/image']
            $.each(arr['/common/topic/image'], function (k, l) {
                console.log(l);
            });
        });
    });
    

    JSFiddle

    来自您的 cmets,

    如果你检查你的json,最后一个result没有名为/common/topic/image的数组。

    所以当它尝试迭代时,它失败了[无法获取长度]

    所以只需向它添加一个条件,例如if (arr['/common/topic/image']) {...}。现在,如果它有空元素,它将被跳过。

    检查这个小提琴http://jsfiddle.net/praveen_jegan/6MCKA/2/

    【讨论】:

    • 感谢 Praveen Jeganathan。
    • @ARV 很高兴能帮上忙,我的朋友。
    • 你好 Praveen Jeganathan 我收到错误消息,即 $.each(arr['/common/topic/image'],函数(索引,图片){}
    • @ARV 如果您检查 json 中的最后一个结果,则没有名为 /common/topic/image 的数组。因此,当它尝试迭代时,它失败了。因此,只需向它添加一个条件,例如 `if (arr['/common/topic/image']) {...}`。现在它有空元素,它将被跳过。现在检查这个小提琴jsfiddle.net/praveen_jegan/6MCKA/2。希望你能理解。
    • 感谢 Praveen Jeganathan。现在它工作正常。感谢您的指导。
    【解决方案2】:

    如果对象键包含点或斜线,您可以通过这种方式访问​​它:

    var o = {
     'some.key': 123,
     'another/key': 321
    };
    
    console.log(o['some.key'], o['another/key']);
    

    【讨论】:

      猜你喜欢
      • 2022-07-07
      • 2014-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多