Load a JSON File from a URL request

Viewed 1041

Currently, I am using the code below to load a JSON file. However, I want to load the JSON data without saving a file to my laptop. I tried directly to load however it is giving me an error.

First Code:

url = "example.url"
response = requests.request("GET", url, headers=headers)
with open('save.json', 'wb') as outf:
    outf.write(response.content)
file = open("save.json")
data = json.load(file)

Code Tried:

url = "example.url"
response = requests.request("GET", url, headers=headers)
data = json.load(response.content)

Error:

AttributeError: 'bytes' object has no attribute 'read'
2 Answers

You can do that directly from your response object.

response.json()

Note that it will raise an error if the content of the response is not in a valid json format.

url = "example.url"
response = requests.request("GET", url, headers=headers)

data = response.json()
Related