Access JSON item when parent key name is unknown

天大地大妈咪最大 提交于 2020-01-14 00:35:11

问题


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

The response looks like this:

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

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


回答1:


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

  • 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].

Solution> 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");

Encouraging +1 welcome.




回答2:


In javascript you can:

var a; // assume that a is your json
var title;
for (var obj in a["query"]["pages"])
{
  if (a["query"]["pages"][obj].title != undefined)
  {
   title = a["query"]["pages"][obj].title;
   break;
  }
}


来源:https://stackoverflow.com/questions/19608227/access-json-item-when-parent-key-name-is-unknown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!