在 python 中打开 json.gz

Open json.gz in python

我正在尝试访问 json 对象,该对象以压缩 gz 格式存储在 html 网站上。如果可能的话,我想直接用 urllib 来做。

这是我试过的:

import urllib
import json

#get the zip file
test = urllib.request.Request('http://files.tmdb.org/p/exports/movie_ids_01_27_2021.json.gz')

#unzip and read
with gzip.open(test, 'rt', encoding='UTF-8') as zipfile:
    my_object = json.loads(zipfile)

但这失败了:

TypeError: filename must be a str or bytes object, or a file

可不可以这样直接读取json(比如不想下载到本地)

谢谢。

使用请求库。 pip install requests 如果你没有。

然后使用下面的代码:

import requests

r = requests.get('http://files.tmdb.org/p/exports/movie_ids_01_27_2021.json.gz')
print(r.content)

r.content 将是 gzip 文件的二进制内容,但它会消耗 11352985 字节的内存 (10.8 MB),因为数据需要保存在某个地方。

那么你可以使用

gzip.decompress(r.content)

解压缩 gzip 二进制文件并获取数据。解压后会占用更大的内存