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






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






@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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)