I'm trying to parse a JSON string with
json.loads(json_string)
but it returns a string instead of a dict. I can get the expected result by parsing it again
json.loads(json.loads(json_string))
but I don't understand why.
I receive a bytes object from a webhook:
bytes_object = b'"{\\"action\\":\\"connection_test\\",\\"data\\":{}}"'
The bytes object is then utf-8 decoded:
decoded_bytes = bytes_object.decode('utf-8')
"{\"action\":\"connection_test\",\"data\":{}}"
Then, the utf-8 decoded object is parsed using json.loads:
parsed_once = json.loads(decoded_bytes)
But this doesn't return a dict, but a string object looking like this:
{"action":"connection_test","data":{}}
of type <class 'str'>.
But if I parse it again I get the dict expected from the first try:
parsed_twice = json.loads(parsed_once)
{'action': 'connection_test', 'data': {}}
of type <class 'dict'>.
I suspect it's something about how Python 3.9 handles JSON escaping, but I'm not sure. Any help?
json.dumpstwice).", so the bytestring indeed is a JSON string that contains a JSON representation of an object.json.loadstwice. And it isn't a Python 3.9 problem. The more pressing question is why did the webhook needed to double-encode the data... which isn't answerable in this current state.b'{"action": "connection_test", "data": {}}'. What you are getting is a JSON object that is encoded again to produce a JSON string. The firstjson.loaddecodes the JSON str into a JSON object; the second decodes the JSON object into a Pythondict.