3

I am trying to save a large JSON file into a variable using requests module but only part of the JSON is making it into the variable when using the following:

r = requests.get(url)

r.json()

I see there are ways to save it in chunks when writing to a file is there a way to do this when writing to a variable?

1
  • 1
    "I see there are ways to save it in chunks when writing to a file is there a way to do this when writing to a variable?" — No. Without more information (e.g., what you expect to be in the variable versus what's actually ending up in there), we can't tell you what's going wrong. Commented Dec 1, 2017 at 4:49

2 Answers 2

4

According to the docs , using 'with' and setting stream to True should get you what you need.

with requests.get('http://httpbin.org/get', stream=True) as r:
    # Do things with the response here.
Sign up to request clarification or add additional context in comments.

Comments

1
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()

Or you can use context manager:

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)

Update:

To a variable, it is the same, just use data += chunk

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.