python - 读取压缩的 JSON 文件

标签 python python-3.x

我从 openFDA 下载了 2015 年药物不良事件数据,我想用 Python 运行一些分析。

我无法使 JSON 解码正常工作。

我可以找到 gzip 的代码片段,但不能找到普通 zip 文件的代码片段。

我得到的错误信息是:

TypeError: the JSON object must be str, not 'bytes'

JSON 文件很大。 jsonstreamerijson 或其他库是推荐的工具吗?

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/

相关文章:

Python - 输入验证

python selenium 无法清除输入字段

python - 这个 python for 循环和 if 语句表现得很奇怪

python - 引用python中的列表容器理解for循环

python - 当函数返回pandas数据帧时,如何在python中编写并行枚举for循环

python - 将应用名称导入项目 urls.py Django

python - 在具有不同变量的多个内核中运行类似程序

python - 如何在 sympy 的表达式中替换多个符号?

python - py2exe/cx_Oracle - 生成的 dist 中的 OCI.dll

python - Selenium 中的下拉菜单 - Python 3