如何使用Python中的请求模块获取大型JSON文件

时间:2017-12-01 04:41:08

标签: python json python-requests

我正在尝试使用JSON模块将大requests个文件保存到变量中,但在使用以下内容时,只有部分JSON正在将其变为变量:

r = requests.get(url)

r.json()

我看到有些方法可以在写入文件时将其保存在块中是否可以在写入变量时执行此操作?

2 个答案:

答案 0 :(得分:1)

根据docs,使用''并将流设置为True应该可以满足您的需求。

with requests.get('http://httpbin.org/get', stream=True) as r:
    # Do things with the response here.

答案 1 :(得分:0)

response = requests.get(url, stream=True)
with open(path, 'wb') as f:
    for chunk in response.iter_content(chunk_size=1024):
        if chunk:  # filter out keep-alive new chunks
            f.write(chunk)
response.close()

或者您可以使用上下文管理器:

with requests.get(url, stream=True) as response:
    with open(path, 'wb') as f:
        for chunk in response.iter_content(chunk_size=1024):
            if chunk:  # filter out keep-alive new chunks
                f.write(chunk)

更新

对于变量,它是相同的,只需使用data += chunk