Parse all bytearray values in a JSON in Python
Parse all bytearray values in a JSON in Python
I have a complex object that has some properties of bytearray
type and when I try to convert it to JSON it throws this error:
bytearray
TypeError: Object of type bytearray is not JSON serializable.
I can make a method hardcoding the properties that I know that are bytearray
type and then do this:
bytearray
bytes(key.key_value).decode("utf-8")
The problem is that I have lots of possible cases and I'd like to make a generic method that allows me to parse all bytearray
properties of a JSON to string
.
I tried to make my own json.JSONEncoder
implementation but it didn't work. Any suggestion? Thanks in advance!
bytearray
string
json.JSONEncoder
@wim I don't care since I only want to show the decoded value in a console
– Nahue
Sep 7 '18 at 21:26
OK, so you don't need to load the json in again? You just want the bytearray to look like a string in the output?
– wim
Sep 7 '18 at 21:28
@wim Yes! That's exactly what I want.
– Nahue
Sep 7 '18 at 21:34
1 Answer
1
Decide on the encoding and error handling behaviour that you want to use for decoding bytearrays to strings, and then:
import json
class FunkyJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, bytearray):
return obj.decode("utf-8", errors="replace")
else:
return super().default(obj)
Usage example:
>>> dumps = FunkyJSONEncoder().encode
>>> dumps('k': bytearray(b'potato'))
'"k": "potato"'
It didn't work: TypeError: Object of type MyType is not JSON serializable. However, I made it work with another solution I came up with. Thanks anyway!
– Nahue
Sep 7 '18 at 21:57
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Basically this is just not supported in json. How will you tell the difference between bytearrays and strings when loading data?
– wim
Sep 7 '18 at 21:12