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

Accessing nested data in a Wiki API JSON response

我对这一切还比较陌生,但我正在尝试访问维基百科的 API 以检索 "extract" 的值并将文本附加到 html元素。问题是 "pages" 会根据用户输入而改变。有没有办法访问给定 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."
        }
    }
}

}

Extract 随机编号 哈希中的哈希,它位于 pages 哈希,它位于 query 哈希的内部。所以你需要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 数据。