1

I am trying to save data received from API in file in json format.

response = requests.get(url_league,   headers= header)
type(response)
#output requests.models.Response
with open("json.txt", "w+") as f:
    data = json.dump(response, f)

When i trying to save response object to file i got the following error

Object of type Response is not JSON serializable

I read that json module have problems with encoding complex objects and for this purposes in json have default function to encode complex objects. I tried the following code

json_data = json.dump(response.__dict__, f, default = lambda o: o.__dict__, indent=4)

And got the following error

bytes' object has no attribute '__dict__'

What this error mean and how to solve it?

2
  • 1
    have you tried using response.json()? Commented Jul 26, 2019 at 15:54
  • Wonderfull) i tried and get what i want. Thank you man Commented Jul 26, 2019 at 15:56

1 Answer 1

2

The error you're getting means that response is of type "bytes", and not text/JSON. You need to decode your response first (you need urllib or urllib2).

import json
import urllib.request

response=urllib.request.urlopen(url_league).read()
string = response.decode('utf-8')
json_obj = json.loads(string)

with open("json.txt", "w+") as f:
    data = json.dump(json_obj, f)

To use headers you can just use

req = Request(url)
req.add_header('apikey', 'xxx')
Sign up to request clarification or add additional context in comments.

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.