Deserialize a json string to an object in python
I have the following string
{"action":"print","method":"onData","data":"Madan Mohan"}
I Want to deserialize to a object of class
class payload
string action
string method
string data
I am using python 2.6 and 2.7
Solution 1:
>>> j = '{"action": "print", "method": "onData", "data": "Madan Mohan"}'
>>> import json
>>>
>>> class Payload(object):
... def __init__(self, j):
... self.__dict__ = json.loads(j)
...
>>> p = Payload(j)
>>>
>>> p.action
'print'
>>> p.method
'onData'
>>> p.data
'Madan Mohan'
Solution 2:
To elaborate on Sami's answer:
From the docs:
class Payload(object):
def __init__(self, action, method, data):
self.action = action
self.method = method
self.data = data
import json
def as_payload(dct):
return Payload(dct['action'], dct['method'], dct['data'])
payload = json.loads(message, object_hook = as_payload)
My objection to the
.__dict__
solution is that while it does the job and is concise, the Payload class becomes totally generic - it doesn't document its fields.
For example, if the Payload message had an unexpected format, instead of throwing a key not found error when the Payload was created, no error would be generated until the payload was used.