到达JSON中未知值后面的字符串 [英] Reach a string behind unknown value in JSON

查看:78
本文介绍了到达JSON中未知值后面的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Wikipedia的API获取有关页面的信息. 该API给了我这样的JSON:

I use Wikipedia's API to get information about a page. The API gives me JSON like this:

"query":{
  "pages":{
     "188791":{
        "pageid":188791,
        "ns":0,
        "title":"Vanit\u00e9",
        "langlinks":[
           {
              "lang":"bg",
              "*":"Vanitas"
           },
           {
              "lang":"ca",
              "*":"Vanitas"
           },
           ETC.
        }
     }
  }
}

您可以看到我想获取所有条目,例如:

I want to obtain all entries like:

{
   "lang":"ca",
   "*":"Vanitas"
}

,但是pages对象中的数字键("188791")是问题.

but the number key ("188791") in the pages object is the problem.

我找到了在python的嵌套json字典中找到一个值解释了如何枚举值.

I found Find a value within nested json dictionary in python that explains me how to do enumerate the values.

不幸的是,我得到以下异常:

Unfortunately I get the following exception:

TypeError: 'dict_values' object does not support indexing

我的代码是:

json["query"]["pages"].values()[0]["langlinks"]

这可能是一个愚蠢的问题,但我找不到传递页面ID值的方法.

It's probably a dumb question but I can't find a way to pass in the page id value.

推荐答案

只要您一次只查询一页, Simeon Visser的答案将起作用.但是,作为一种好的样式,我建议对代码进行结构化,以便对所有返回的结果进行迭代,即使您知道应该只有一个:

As long as you're only querying one page at a time, Simeon Visser's answer will work. However, as a matter of good style, I'd recommend structuring your code so that you iterate over all the returned results, even if you know there should be only one:

for page in data["query"]["pages"].values():
    title = page["title"]
    langlinks = page["langlinks"]
    # do something with langlinks...

特别地,通过以这种方式编写代码,如果发现自己需要对多个页面运行查询,则可以通过单个MediaWiki API请求来高效地完成此操作.

In particular, by writing your code this way, if you ever find yourself needing to run the query for multiple pages, you can do it efficiently with a single MediaWiki API request.

这篇关于到达JSON中未知值后面的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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