I have an array of custom objects (lightning records) that I serialize without any problems with my custom encoder:
class LightningJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Lightning):
dct = dict()
dct['type'] = 'Feature'
...
return dct
return json.JSONEncoder.default(self, obj) # pragma: no cover
This serializes an array of Lightnings as:
[{"type": "Feature", ...}, ..., {...}]
But I need to add more data, the number of Lightnings and another type, such as:
{
"type": "FeatureCollection",
"number_of_features": 3,
"features": [{"type": "Feature", ...}, ..., {...}]
}
So, if I try to serialize:
json.dumps([lightning, lightning, lightning], cls=LightningJSONEncoder)
It gives me the first output and I have to manually add a new dict get the second output.
lights = [lightning1, lightning2, lightning3]
dct = {
"type": "FeatureCollection",
"number_of_features": len(lights),
"features": lights
}
json.dumps(dct, cls=LightningJSONEncoder)
How can I get this behaviour but inside a custom JSONEncoder
class? I've read about the iterencode
but I don't get it.
Thank you.