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

时间:2012-09-11 13:10:31

标签: python json class

这是我的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类数组。

如何实例化这些并妥善存储数据?

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

2 个答案:

答案 0 :(得分:13)

看看colander;它使得将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)) 

答案 1 :(得分:1)

如果您使用的是Python 3.6+,则最简单的方法可能是使用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)