Json.dump rename object before dump

I am currently serializing my custom object to a JSON string using json.dumps() .

 j = json.dumps(object, sort_keys=True, indent=4, separators=(',', ': '), default=lambda o: o.__dict__) 

My object has a _machines attribute. Therefore, when we turn an object into a string, one of the properties in the string is called _machines . Is there a way to tell json.dump() that we want this property to be called machines , not _machines ?

0
source share
1 answer

You will need to use a more complex default value:

 json.dumps(object, sort_keys=True,indent=4, separators=(',', ': '), default=lambda o: {'machines' if k == '_machines' else k: v for k, v in o.__dict__.iteritems()}) 

It might be a good idea, for readability, to make this separate function:

 def serialize_custom_object(o): res = o.__dict__.copy() res['machines'] = res['_machines'] del res['_machines'] return res json.dumps(object, sort_keys=True,indent=4, separators=(',', ': '), default=serialize_custom_object) 

Here serialize_custom_object() is a little more explicit that you rename one key to the result.

+2
source

All Articles