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.
source share