TypeError: the JSON object must be str, not 'bytes'
json.loads(myResponse.content.decode('utf-8'))
You just put it in the wrong order, innocent mistake.
(In-depth answer). As courteously pointed out by wim, in some rare cases, they could opt for UTF-16 or UTF-32. These cases will be less common as the developers, in that scenario would be consciously deciding to throw away valuable bandwidth. So, if you run into encoding issues, you can change utf-8 to 16, 32, etc.
There are a couple of solutions for this. You could use request's built-in .json()
function:
myResponse.json()
Or, you could opt for character detection via chardet
. Chardet is a library developed based on a study. The library has one function: detect
. Detect can detect most common encodings and then use them to encode your string with.
import chardet
json.loads(myResponse.content.decode(chardet.detect(myResponse.content)["encoding"]))
TypeError: the JSON object must be str, not 'bytes' - Python - fixer.io
[Python 3.Docs]: json.loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) states:
Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.
urllib.request.urlopen
returns a http.client.HTTPResponse
object.
According to [Python 3.Docs]: http.client - HTTPResponse.read([amt]):
Reads and returns the response body, or up to the next amt bytes.
So, in order to make this work, you have to convert the bytes into str
(via [Python 3.Docs]: bytes.decode(encoding="utf-8", errors="strict")):
rdata = json.loads(data.decode(), parse_float=float)
Note:
- Starting with Python 3.6,
json.loads
is able to also handle bytes
Regarding your other error, I remember (as I once worked with Flask) that the Response objects only had a json method, if the HTTP status code was 200 (OK). But I'm not sure it's the same object that we're talking about, since I was using the requests module.
how to solve : TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper
You are using loads
when you need load
. json.load
is for file-like objects, and json.loads
is for strings. (You could also load the string into memory and then parse it with json.load
, but you don't want to do that).
Also, please don't post screenshots! They're harder to make sense of, and require clicking.
TypeError: the JSON object must be str, not 'bytes' - Python3.x
In python3 retrieving 'data' from a source returns bytes instead of a string. So you have to decode it
Try:
response = urllib.request.urlopen('http://freegeoip.net/json/')
info = load(response.decode('utf-8'))
Beyond that, I would strongly suggest using requests instead of urllib.
It tends to be a bunch more intuitive.
import requests # 'pip3 install requests --user' beforehand to install it
response = requests.get('http://freegeoip.net/json/')
response.json() # Fully parsed and loaded as a Dict/JSON Object
Also if that doesn't work, then there is some other alternatives, per a similar question on Stack Overflow here.
Alternatives here
Use load
on the text, the response.json()
should be a Dict if all went right with parsing and if the server returned the right headers.
Link to requests
docs here
Getting TypeError: the JSON object must be str, bytes or bytearray, not NoneType
Currently, getinfo() has no return statement so it returns NoneType.
You should use return instead of print the data only.
Related Topics
How to Verify If a Button Is Enabled and Disabled in Webdriver Python
How to Run External Executable Using Python
How to Repeatedly Execute a Function Every X Seconds
Bold Formatting in Python Console
How to Get the Sum of a CSV Column List to Print
How to Open a Password Protected Excel File Using Python
How to Remove \N from a List Element
Adding a Data File in Pyinstaller Using the Onefile Option
Python Get File Size of Volumes or Physical Drives
Python Creating Dictionary from Excel Data
Remove White Space from Entire Dataframe
How to Count Occurrences of Key in List of Dictionaries
Python + Beautifulsoup: How to Get 'Href' Attribute of 'A' Element
Python Pandas .Isnull() Does Not Work on Nat in Object Dtype
Making a Matrix in Python 3 Without Numpy Using Inputs
How to Extract X,Y Coordinates from Opencv "Cv2.Keypoint" Object