python json serialize object code example

Example 1: python class json serializable

import json

class Object:
    def toJSON(self):
        return json.dumps(self, default=lambda o: o.__dict__, 
            sort_keys=True, indent=4)

Example 2: python json serialize object

import json
info = {
    "data": {
        "name": "Dave",
        "City": "NY"
    }
}
# With json.dump  (into file)
with open( "data.json" , "w" ) as x:
    json.dump( info , x )
# >>> {"data": {"name": "Dave", "City": "NY"}}

# with json.dumps (object)
data = json.dumps( info )
print( data )
# >>> {"data": {"name": "Dave", "City": "NY"}}