【问题标题】:(ijson) Getting item with any prefix(ijson) 获取任何前缀的项目
【发布时间】:2020-02-20 14:25:56
【问题描述】:

我有一个这样的 json 文件:

{
    "europe": [
      "germany",
      "france",
      ...
    ],
    "america": [
      "usa",
      "canada",
      ...
    ]
  }

我想像这样获取每个前缀的所有项目:

germany
france
usa
canada

我用这个:

with open('file.json', 'r', encoding='utf-8') as f:
    for object in ijson.items(f, "item"):
        print (object)

我尝试使用接受item 前面的每个字符串的正则表达式,但它不起作用。我认为有一个非常简单的解决方案,我只是看不到。也查看了ijson的文档,也没有找到解决办法。

也许你可以帮助我。

问候

【问题讨论】:

    标签: python prefix ijson


    【解决方案1】:

    我是否理解正确,您只是想要一份不包括大陆的所有国家/地区的列表?

    import json
    with open('file.json', 'r', encoding='utf-8') as f:
        countries = [con for coun in json.load(f).values() for con in coun]
    print(countries)
    

    【讨论】:

    • 完全正确。但我想使用像 ijson 这样的迭代 json 解析器,因为 json 文件很大。那么有没有可能使用我的 ijson 方法?
    【解决方案2】:

    目前无法使用 items 执行此操作,因为它不支持通配符或深度规范。您可以毫不费力地获得最接近(使用 2.6)的方法:

    for continent, countries in ijson.kvitems(f, ''):
       for country in countries:
          print(country)
    

    如果单个国家/地区列表本身太大而无法保存在内存中,您将不得不采用基于ijson.parse() 的更加手动的方法来跟踪您的路径的“深度”。

    【讨论】:

      猜你喜欢
      • 2011-09-13
      • 2020-11-26
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      相关资源
      最近更新 更多