一尘不染

解析JSON并将数据存储在Python类中

json

这是我的JSON数据

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

我有两个Python类

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

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

我需要解析JSON数据并实例化适当的类。类是不言自明的:即Person具有一系列Character类。

如何实例化它们并适当地存储数据?

另外,我将如何访问特定的人员数据?即人的细节和特征


阅读 282

收藏
2020-07-27

共1个答案

一尘不染

看看漏勺 ;
它使得将JSON数据结构转换为Python对象变得非常容易。

您定义一个架构:

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

然后使用以下命令传入您的JSON数据结构:

deserialized = Data.deserialize(json.loads(json_string))
2020-07-27