>>> 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'
Answer from John La Rooy on Stack Overflow>>> 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'
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.
De/Serializing JSON In Python, While Keeping Your Types
For fun, I created a library to serialize / deserialize any python object into JSON
serialization and deserialization question
Serialize/deserialize (JSON) class attributes recursively across hierarchy of classes.
Videos
Short writeup of the motivations I had for writing a Python serialization library
https://medium.com/@steffen.cucos/de-serializing-json-in-python-4053366bc8ad
Coming from the world of Java I was used to dealing with external systems like DBs & APIs that communicate over varying messaging formats, but the details of how an object was sent or received over the wire was always hidden behind libraries that handled the process of turning a Java object into JSON & JSON back into a real Java object.
In Python it seems like the general approach to this serialization issue is to manually handle turning objects into JSON (hand written to_json, JSON.dumps(obj.__dict__ ), etc.), and to manually reconstruct an instance of an object for deserialization.
In a personal project of mine I ran into this issue on 2 fronts. Sending/Receiving data over an API, and saving/reading data from mongodb.
In order to solve the issue, I wrote a library called pserialization to automate the task of turning objects into JSON, and turning JSON back into an object.
The serialization part is actually fairly simple. Much like the JSON.dumps(obj.__dict__) approach, the library recursively serializes each field in an objects __dict__ attribute, and uses the type of each field to inform what JSON primitive to serialize into (int, float, bool, array, {}).
The deserialization part is more complicated, and requires you to tell the library what object you want to turn some JSON into, and to have type hints (either as a dataclass or in the __init__ of the object). Using the type information the library can know which types need to be instantiated and with which fields.
TLDR:
Upset that there is no generic way to convert from python objects to JSON and back, so wrote a library that uses type hints to automate the de/serialization process.
Source code:
https://github.com/SteffenCucos/PSerialization
» pip install deserialize
It's a fun little side project I did today, the goal being to be able to serialize and deserialize any object into and from the JSON format.
To do so, I've built the library in 3 components : a JSONDecoder, JSONEncoder and a serializable decorator. Simply decorate a class with the decorator, and you'll be able to save/restore that exact object from a JSON file.
Let me know what you think ! https://github.com/Dogeek/picklejson