Parse JSON and store data in Python Class

2020-02-10 07:27发布

问题:

This is my JSON data

[
    {
        "id":1,
        "name":"abc",
        "phone": "12345",
        "Charecteristics": [
            {
                "id":1,
                "name":"Good Looking",
                "rating": "Average",
            }
            {
                "id":2,
                "name":"Smart",
                "rating": "Excellent",
            }
        ]
    },
    { ... },
    { ... }
]

I have two Classes in Python

class Character(object):
    id = 0
    name = ""
    rating = ""

class Person(object):
    id = 0
    name = ""
    phone = ""
    Characteristics = []

I need to parse the JSON data and instantiate appropriate Classes. The Classes are self-explanatory: i.e. Person has an array of Character classes.

How do I instantiate these and store data appropriately?

Also, how will I access particular Person data? i.e. Person's details and characteristics

回答1:

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)) 


回答2:

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)