访问Wiki API JSON响应中的嵌套数据

时间:2019-05-22 01:18:52

标签: javascript jquery json parsing wikipedia-api

对于这一切,我还是相对较新,但是我试图访问Wikipedia的API,以便检索“提取”的值并将文本附加到html元素。问题是“页面”将根据用户输入而改变。在JSON响应中给定随机数的情况下,是否可以访问信息? *编辑-我正在使用Jquery / Javascript。 这是我发送的API请求: https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=Pug

{

"batchcomplete": "",
"query": {
    "normalized": [
        {
            "from": "pug",
            "to": "Pug"
        }
    ],
    "pages": {
        "21234727 (this number is will change/be random)": {
            "pageid": 21234727,
            "ns": 0,
            "title": "Pug",
            "extract": "The pug is a breed of dog with physically distinctive features of a wrinkly, short-muzzled face, and curled tail. The breed has a fine, glossy coat that comes in a variety of colours, most often fawn or black, and a compact square body with well-developed muscles.\nPugs were brought from China to Europe in the sixteenth century and were popularized in Western Europe by the House of Orange of the Netherlands, and the House of Stuart. In the United Kingdom, in the nineteenth century, Queen Victoria developed a passion for pugs which she passed on to other members of the Royal family.\nPugs are known for being sociable and gentle companion dogs. The American Kennel Club describes the breed's personality as \"even-tempered and charming\". Pugs remain popular into the twenty-first century, with some famous celebrity owners. A pug was judged Best in Show at the World Dog Show in 2004."
        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

提取随机编号哈希中的哈希,该哈希位于 pages 哈希中,该哈希位于查询。因此,您需要json->query->pages->random_number->extract的值。

这需要给随机数起一个名字,以便您每次都知道如何引用它。您没有说使用什么语言,但是我会在Perl中尝试这样的操作(如果您提供选择的语言,其他人可以显示对应的操作):

foreach my $pagenum ( keys %{$json{'query'}{'pages'}}) {
  print "Random number is now called $pagenum\n"; 
my $extract = $json{'query'}{'pages'}{$pagenum}->{'extract'}; 
  print "Extract is $extract\n";
}

打印$extract的结果是: The pug is a breed of dog with physically distinctive features of a wrinkly...

我让我的儿子将Perl操作转换为Ruby,因此也可以使用。 (假设JSON位于名为json的变量中):

randnum = json['query']['pages'].keys[0]
extract_value = json['query']['pages'][randnum]['extract']
puts extract_value

更新 :( OP指定的语言)

我不太喜欢Javascript,但这似乎行得通:

var extractValue = Object.values(your_json.query.pages)[0].extract; (其中 your_json 是您收到的JSON数据)。