Parse JSON and store data in Python Class

2020-02-10 07:54发布

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

2条回答
仙女界的扛把子
2楼-- · 2020-02-10 08:00

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)
查看更多
贼婆χ
3楼-- · 2020-02-10 08:26

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)) 
查看更多
登录 后发表回答