父键名称未知时访问JSON项目 [英] Access JSON item when parent key name is unknown

查看:98
本文介绍了父键名称未知时访问JSON项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过Wikipedia的API请求JSON

I’m requesting JSON from Wikipedia’s API at

http://en.wikipedia.org/w/api.php?action=query&prop=description&titles=WTO&prop=extracts&exsentences&explaintext&format=json

响应如下:

{
    "query": {
        "pages": {
            "ramdom_number_here": {
                "pageid": ramdom_number_here,
                "ns": 0,
                "title": "Hello",
                "extract": "Hello world! Enchanté to meet you"
            }
        }
    }
}

鉴于ramdom_number_here更改了每个请求(因此我们不知道),如何访问extractitle的数据?

Given that ramdom_number_here changes each request (so we don't know it), how can extrac or title’s data be accessed?

推荐答案

使用Object.keys(data)[x]替换数据路径上的主路径.

Use Object.keys(data)[x] to replace the nominative pathway byt the the coordinate of your data.

  • Object.keys(data)-为您提供该级别的键列表.
  • 然后使用x =目标数据的数字范围.对于第一个数据点,则为[x] = [0].
  • Object.keys(data) -- give you the list of keys at that level.
  • Then use x=the numeral rang of your target data. For the first data point, then [x]=[0].

解决方案> JSfiddle :

function WD(val) { // input
    target_API_url = "http://zh.wikipedia.org/w/api.php?action=query&prop=description&titles=" + val.toString() + "&prop=extracts&exintro&explaintext&format=json&redirects&callback=?";
    $.getJSON(target_API_url, function (json) {
        trad = json.query.redirects[0].to; // no "var", variable is global
        var item_id = Object.keys(json.query.pages)[0]; // THIS DO THE TRICK !
        sent = JSON.stringify(json.query.pages[item_id].extract);
        result = "<b>En:</b> "+val.toString() + ", <b>Zh: </b>"+trad.toString() +  "<br /><b>⇒</b>" + sent.toString();
        $('p').html(result); // transformation 
    });
};
WD("WTO");

鼓励+1欢迎.

这篇关于父键名称未知时访问JSON项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆