Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 - Writing data from struct.unpack into json without individual recasting

I have a large object that is read from a binary file using struct.unpack and some of the values are character arrays which are read as bytes.

Since the character arrays in Python 3 are read as bytes instead of string (like in Python 2) they cannot be directly passed to json.dumps since "bytes" are not JSON serializable.

Is there any way to go from unpacked struct to json without searching through each value and converting the bytes to strings?

like image 758
rovyko Avatar asked Nov 15 '17 20:11

rovyko


1 Answers

You can use a custom encoder in this case. 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"}
like image 180
Tarun Lalwani Avatar answered Nov 01 '22 05:11

Tarun Lalwani