3

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'
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
niko
  • 49
  • 5
  • 1
    Does this answer your question? [How to get JSON from webpage into Python script](https://stackoverflow.com/questions/12965203/how-to-get-json-from-webpage-into-python-script) – Tomerikoo Jan 31 '21 at 12:42

2 Answers2

2

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.

Nerveless_child
  • 1,366
  • 2
  • 15
  • 19
2
url = "example.url"
response = requests.request("GET", url, headers=headers)

data = response.json()
Cosmos
  • 372
  • 2
  • 6