3

我已经下载了一个压缩的 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'
4

2 回答 2

3

在第一个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))

于 2019-06-20T00:38:55.840 回答
1

gzip使用标准库 ( docs )中的包打开文件,然后将其直接读入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")
于 2019-06-20T00:44:34.397 回答