我从 openFDA 下载了 2015 年药物不良事件数据,我想用 Python 运行一些分析。
我无法使 JSON 解码正常工作。
我可以找到 gzip 的代码片段,但不能找到普通 zip 文件的代码片段。
我得到的错误信息是:
TypeError: the JSON object must be str, not 'bytes'
JSON 文件很大。 jsonstreamer
、ijson
或其他库是推荐的工具吗?
JSON 文件如下所示(手动解压后):
{
"meta": {
"last_updated": "2016-11-18",
"terms": "https://open.fda.gov/terms/",
"results": {
"skip": 0,
"total": 304100,
"limit": 25000
},
"license": "https://open.fda.gov/license/",
"disclaimer": "Do not rely on openFDA to make decisions regarding medical care. While we make every effort to ensure that data is accurate, you should assume all results are unvalidated. We may limit or otherwise restrict your access to the API in line with our Terms of Service."
},
这是我的代码:
import json
import zipfile
d = None
data = None
with zipfile.ZipFile("./data/drug-event-Q4-0001-of-0013.json.zip", "r") as z:
for filename in z.namelist():
print(filename)
with z.open(filename) as f:
data = f.read()
d = json.loads(data)
最佳答案
您从压缩文件中读取的数据是字节。 Json 解码器需要的是文本。所以;与往常一样,对于此类问题,您必须将字节解码为字符串,然后再将其提供给 json 模块。
我假设 json 文件以 UTF-8 编码保存,这样就可以解决问题:
d = json.loads(data.decode("utf-8"))
如果您的 json 文件采用不同的编码,请相应地更改字符编码。
关于您的第二个问题:“大”有多大?
关于python - 读取压缩的 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40824807/