Python 3 - Writing data from struct.unpack to json without individual conversion

I have a large object that is read from a binary using struct.unpack, and some of the values ​​are arrays of characters that are considered bytes.

Since character arrays in Python 3 are read as bytes instead of strings (for example, in Python 2), they cannot be directly passed to json.dumps, because "bytes" are not serializable JSON.

Is there a way to go from the decompressed structure to json without searching through each value and converting bytes to strings?

+5
source share
1 answer

In this case, you can use a custom encoder. See below

import json x = {} x['bytes'] = [b"i am bytes", "test"] x['string'] = "strings" x['unicode'] = u"unicode string" class MyEncoder(json.JSONEncoder): def default(self, o): if type(o) is bytes: return o.decode("utf-8") return super(MyEncoder, self).default(o) print(json.dumps(x, cls=MyEncoder)) # {"bytes": ["i am bytes", "test"], "string": "strings", "unicode": "unicode string"} 
+6
source

Source: https://habr.com/ru/post/1273410/


All Articles