Tony Tony - 6 months ago 53
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


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): = 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( #prints 'ruby'
print(gem.type) #prints 'rare'

Answer Source

Use get() with a default value:

self.type = params.get('type', '')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download