zidsal
zidsal

Reputation: 587

json.dump object rename attribute before the dump

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

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

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

Upvotes: 0

Views: 1927

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123950

You'll have to use a more elaborate default:

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 the sake of readability, to make that a 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 are renaming one key in the result.

Upvotes: 3

Related Questions