Parse JSON and store data in Python Class

Take a look at colander; it makes turning a JSON data structure into Python objects dead easy.

You define a schema:

import colander


class Characteristic(colander.MappingSchema):
    id = colander.SchemaNode(colander.Int(),
                             validator=colander.Range(0, 9999))
    name = colander.SchemaNode(colander.String())
    rating = colander.SchemaNode(colander.String())        


class Characteristics(colander.SequenceSchema):
    characteristic = Characteristic()


class Person(colander.MappingSchema):
    id = colander.SchemaNode(colander.Int(),
                             validator=colander.Range(0, 9999))
    name = colander.SchemaNode(colander.String())
    phone = colander.SchemaNode(colander.String())
    characteristics = Characteristics()


class Data(colander.SequenceSchema):
    person = Person()

then pass in your JSON data structure using the following:

deserialized = Data.deserialize(json.loads(json_string)) 

If you are writing in python 3.6+, the easiest is probably to use marshmallow-dataclass :

from marshmallow_dataclass import dataclass
from typing import List

@dataclass
class Character:
    id : int
    name : str
    rating : str

@dataclass
class Person:
    id : int
    name : str
    phone : str
    characteristics : List[Character]

my_person = Person.Schema().loads(json_str)

Tags:

Python

Class

Json