Tony Tony - 1 month ago 13
JSON Question

Python - Create object from JSON with optional key/value parameters

Trying to create objects based on name/value pairs obtained in JSON form

e.g.

json = {'name': 'ruby',
'type': 'rare',
'size': {'weight': '5', 'height': '2'}
}


however the name/values can be optional. So it could also be of the form

json = {'name': 'saph',
'size': {'height': '4'}
#'type' and 'height' have been omitted
}


I attempted

class Gem(object):
def __init__(self, **params):
self.name = params['name']
self.type = params['type']
self.size = params['size']

gem = Gem(**json)


but it is expecting all parameters to be available.

I want to eventually be able to access properties of the object, e.g.

print(gem.name) #prints 'ruby'
print(gem.type) #prints 'rare'

Answer Source

Use get() with a default value:

self.type = params.get('type', '')