0

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?

zidsal
  • 577
  • 1
  • 7
  • 30

1 Answers1

3

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • just a quick comment I was doing this in python3. so __dict__.iteritems() no longer exists. So instead that part should become __dict__.items() except for that it worked perfectly thanks a lot – zidsal Jul 29 '13 at 13:30
  • 1
    Yup, I was indeed assuming Python 2 and forgot to add the usual disclaimer about using `dict.items()` on 3 instead. – Martijn Pieters Jul 29 '13 at 13:38