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

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

本文介绍了解析JSON并将数据存储在Python类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的JSON数据

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



我在Python中有两个类

I have two Classes in Python

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

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

我需要解析JSON数据并实例化相应的类。这些类是不言而喻的:ie Person有一个字符类数组。

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

推荐答案

查看;

你定义一个模式:

import colander


class Characteristic(collander.MappingSchema):
    id = colander.SchemaNode(colander.Int(),
                             validator=colander.Range(0, 9999))
    name = colander.SchemaNode(colander.String())
    rating = colander.SchemaNode(colander.String())


class Characteristics(collander.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(collander.SequenceSchema):
    person = Person()

然后传入您的JSON数据结构:

then pass in your JSON data structure:

deserialized = Data.deserialize(json.loads(json_string))

这篇关于解析JSON并将数据存储在Python类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 20:05