Skip to content
dsun615 edited this page May 17, 2020 · 7 revisions

This is a simple Python package that deserializes json to your custom model include custom attributes and child objects.

It can return a single model or a list of the models. This will allow you to access through the model's attributes.

See the examples below.


Example 1 - String JSON to Custom Object

from json2object import jsontoobject as jo

class Student:
    def __init__(self):
        self.firstName = None
        self.lastName = None
        self.courses = [Course('')]

class Course:
    def __init__(self, name):
        self.name = name

data = '''{
"firstName": "James",
"lastName": "Bond",
"courses": [{
    "name": "Fighting"},
    {
    "name": "Shooting"}
    ]
}
'''

model = Student()
result = jo.deserialize(data, model)
print(result.courses[0].name)

Output

Fighting

Example 2 - JSON Dictionary to Custom Object

from json2object import jsontoobject as jo
import json 

class Student:
    def __init__(self):
        self.firstName = None
        self.lastName = None
        self.courses = [Course('')]

class Course:
    def __init__(self, name):
        self.name = name

data = '''{
"firstName": "James",
"lastName": "Bond",
"courses": [{
    "name": "Fighting"},
    {
    "name": "Shooting"}
    ]
}
'''

model = Student()
d = json.loads(data)
result = jo.deserialize(d, model)
print(f'{result.firstName} {result.lastName} is taking a {result.courses[1].name} course!')

Output

James Bond is taking a Shooting course!

Notes

  • The model class can have default values or have None assigned to it. However, a custom object attribute should be assigned. See Example 1 & 2. The courses attribute is a list and should have one custom object appended to the list. If it's not a list, then assign as normally would.
  • Attribute names should match the json properties. JSON Properties that does not match on the model will be created unless it's name references a custom object attribute on the model.
  • Be aware that the deserializer will populate all nested custom object attributes.