python - 如何在Python中打开json.gz文件并返回字典

标签 python json python-3.x

我下载了一个压缩的 json 文件并希望将其作为字典打开。

我使用了json.load,但数据类型仍然给我一个字符串。 我想从 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'

最佳答案

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

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))

关于python - 如何在Python中打开json.gz文件并返回字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56677516/

相关文章:

python - 为什么 ";"违反格式标准而存在?

ios - 如何在 Swift 4 中使用未知服务器数据类型在对象映射器中属性?

Python-Numpy 矩阵乘法

java - 实体集扩展python

python - 如何让streamHandler每次都覆盖

json - Mule ESB,以类似 JSON 的格式返回数据库连接器数据

json - 时间 JSON 编码为 0 时间

python - 如何创建 pandas "link"(href) 样式?

正则表达式上的 Python TypeError

python - 为什么这个简单的 python toast 通知不起作用?