Python Forum
Byte Error when working with APIs
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Byte Error when working with APIs
#1
I was working with an API: Returns Json array of Tags

r = requests.get('https://cataas.com/api/tags')
    if r.status_code == 200:
        with open(f'{log_Dir}Cat tags.json', 'w') as file:
            json.dump(r.content, file)
This code returns an error:
Error:
raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type bytes is not JSON serializable
I think it is because the data is retrieved in Bytes??
When I try print(type(r.content)) within the function:
Output:
<class 'bytes'>
How is this possible, since when I visit the above url, I get a string of an array?

Any help is appreciated. Thanks.
Reply
#2
Why aren't you using r.json() to deserialise the body into a Python data structure?
Oshadha likes this post
Reply
#3
Instead of r.content which returns bytes, use r.text which returns a str.

However I do not understand why you are using json.dump at all. r.text is a json format str. json.dump() converts an object to a json format str. If you just want to write the json str from request to a file, just write r.text to the file. If you aren't converting json to an object or an object to json, there is no reason to use the json library.
Oshadha likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 error from Mysql call AkaAndrew123 1 3,439 Apr-28-2021, 08:16 AM
Last Post: AkaAndrew123
  'utf-8' codec can't decode byte 0xe2 in position 122031: invalid continuation byte tienttt 12 11,514 Sep-18-2020, 10:10 PM
Last Post: tienttt
  'utf-8' codec can't decode byte 0xda in position 184: invalid continuation byte karkas 8 31,648 Feb-08-2020, 06:58 PM
Last Post: karkas
  Connecting 2 APIs kamaleon 2 2,047 Dec-27-2019, 08:06 AM
Last Post: kamaleon
  charmap codec can't decode byte error with gzipped file in python bluethundr 2 3,713 Apr-30-2019, 12:26 PM
Last Post: bluethundr
  4 byte hex byte swap from binary file medievil 7 22,069 May-08-2018, 08:16 AM
Last Post: killerrex
  Error handling not working desudesu 2 3,474 Jun-14-2017, 02:12 PM
Last Post: desudesu
  With Python I cannot calculate an AWS signature for Rest APIs Johno 4 6,479 Oct-06-2016, 11:05 AM
Last Post: Johno

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020