【问题标题】:Accessing nested data in a Wiki API JSON response访问 Wiki API JSON 响应中的嵌套数据
【发布时间】:2019-10-08 10:17:36
【问题描述】:

我对这一切还比较陌生,但我正在尝试访问 Wikipedia 的 API 以检索“extract”的值并将文本附加到 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."
        }
    }
}

}

【问题讨论】:

  • 你用什么语言来解析 json?
  • 抱歉,感谢您的回复。我正在使用 JQuery/Javascript。
  • 您好,我更新了答案以包含 Javascript 版本。

标签: javascript jquery json parsing wikipedia-api


【解决方案1】:

Extract随机编号 散列内的散列,该散列位于 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 数据)。

【讨论】:

  • 太棒了!非常感谢您的帮助,我非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-23
  • 1970-01-01
  • 1970-01-01
  • 2021-07-02
  • 2020-02-07
  • 2021-03-02
  • 1970-01-01
相关资源
最近更新 更多