解析在Python类JSON和存储数据(Parse JSON and store data in P

2019-06-28 05:03发布

这是我的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数据和实例化适当的类。 这些类是不言自明的:即人具有字符类的阵列。

如何适当地举例说明这些和存储数据?

另外,我怎么会访问特定的人的数据? 即人的细节和特点

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


Answer 2:

如果您在Python 3.6 +写作,最简单的可能是使用棉花糖数据类 :

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)


文章来源: Parse JSON and store data in Python Class