读取压缩的JSON文件

时间:2016-11-27 01:06:07

标签: 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)  

1 个答案:

答案 0 :(得分:5)

您从zipfile读取的数据是字节。 Json解码器需要文本。所以;像往常一样,在将这些字节提供给json模块之前,你必须字节解码成字符串。

我假设json文件以UTF-8编码保存,所以这样就可以了:

d = json.loads(data.decode("utf-8"))

如果您的json文件使用不同的编码,请相应地更改字符编码。

关于你的第二个问题:“大”有多大?

相关问题