【问题标题】:How to open a json.gz file and return to dictionary in Python如何在 Python 中打开 json.gz 文件并返回字典
【发布时间】:2019-06-20 00:30:23
【问题描述】:

我已经下载了一个压缩的 json 文件,想把它作为字典打开。

我使用了json.load,但数据类型仍然给了我string。 我想从 json 文件中提取关键字列表。即使我的数据是字符串,有没有办法可以做到这一点? 这是我的代码:

import gzip
import json
with gzip.open("19.04_association_data.json.gz", "r") as f:

 data = f.read()
with open('association.json', 'w') as json_file:  
     json.dump(data.decode('utf-8'), json_file)

with open("association.json", "r") as read_it: 
     association_data = json.load(read_it) 



print(type(association_data))

#The actual output is 'str' but I expect it is 'dic'

【问题讨论】:

    标签: python json python-3.x


    【解决方案1】:

    在第一个 with 块中,您已经获得了未压缩的字符串,无需再次打开它。

    import gzip
    import json
    
    with gzip.open("19.04_association_data.json.gz", "r") as f:
       data = f.read()
       j = json.loads (data.decode('utf-8'))
       print (type(j))
    
    

    【讨论】:

      【解决方案2】:

      使用标准库 (docs) 中的gzip 包打开文件,然后将其直接读入json.loads()

      import gzip
      import json    
      
      with gzip.open("19.04_association_data.json.gz", "rb") as f:
          data = json.loads(f.read(), encoding="utf-8")
      

      【讨论】:

      • 我再次转储数据,因为一旦我在上面运行您的代码,它就会显示“json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 2350)”。我在想,因为我的 gz 文件有多个 json 对象,所以我将它们全部转储到一个文件中。
      • @CarolineCheng 我想你有一个列表,json 不支持。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多