I am trying to serialize the output of parsing some binary data with the Construct2.9 library. I want to serialize the result to JSON.
packet
is an instance of a Construct class Container
.
Apparently it contains a hidden _io
of type BytesIO
- see output of dict(packet)
below:
{
'packet_length': 76, 'uart_sent_time': 1, 'frame_number': 42958,
'subframe_number': 0, 'checksum': 33157, '_io': <_io.BytesIO object at 0x7f81c3153728>,
'platform':661058, 'sync': 506660481457717506, 'frame_margin': 20642,
'num_tlvs': 1, 'track_process_time': 593, 'chirp_margin': 78,
'timestamp': 2586231182, 'version': 16908293
}
Now, calling json.dumps(packet)
obviously leads to a TypeError:
...
File "/usr/lib/python3.5/json/__init__.py", line 237, in dumps
**kw).encode(obj)
File "/usr/lib/python3.5/json/encoder.py", line 198, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python3.5/json/encoder.py", line 179, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <_io.BytesIO object at 0x7f81c3153728> is not JSON serializable
However what I am confused about, is that running json.dumps(packet, skipkeys=True)
results in the exact same error, while I would expect it to skip the _io
field. What is the problem here? Why is skipkeys
not allowing me to skip the _io
field?
I got the code to work by overriding JSONEncoder
and returning None
for fields of BytesIO
type, but that means my serialized string contains loads of "_io": null
elements, which I would prefer not to have at all...