使用棉花糖在JSON反序列化中的嵌套类

时间:2019-03-09 20:48:11

标签: python json deserialization marshmallow

如何使用棉花糖反序列化嵌套JSON,以便可以使用secondTable之类的点表示法?当前,我的示例仅向下一级提供,但无法从嵌套的app.data.person.lname结构中获取姓氏(lname):

person

获取:

from marshmallow import Schema, fields, post_load
import datetime as dt
import json

class Person(object):
    def __init__(self, fname, lname):
        self.fname = fname
        self.lname = lname

class PersonSchema(Schema):
    fname = fields.Str()
    lname = fields.Str()

class App(object):
    def __init__(self, appid, channel, person):
        self.appid = appid
        self.channel = channel
        self.person = person
        self.created_at = dt.datetime.now()

class AppSchema(Schema):
    appid = fields.Str()
    channel = fields.Str()
    person = fields.Nested(PersonSchema)
    created_at = fields.DateTime()

    @post_load
    def make_user(self, data):
        return App(**data)

json_data = """{
    "appid": "2309wfjwef",
    "channel": "retail",
    "person": {
        "fname": "John",
        "lname": "Doe"
        }
}"""

app_data = json.loads(json_data)

schema = AppSchema()
app = schema.load(app_data)

print(app.data.person.lname)

1 个答案:

答案 0 :(得分:0)

显然,您需要在Person中创建PersonSchema

from marshmallow import Schema, fields, post_load
import datetime as dt
import json

class Person(object):
    def __init__(self, fname, lname):
        self.fname = fname
        self.lname = lname

class PersonSchema(Schema):
    fname = fields.Str()
    lname = fields.Str()

    @post_load
    def make_person(self, data):
        return Person(**data)


class App(object):
    def __init__(self, appid, channel, person):
        self.appid = appid
        self.channel = channel
        self.person = person
        self.created_at = dt.datetime.now()

class AppSchema(Schema):
    appid = fields.Str()
    channel = fields.Str()
    person = fields.Nested(PersonSchema)
    created_at = fields.DateTime()

    @post_load
    def make_app(self, data):
        return App(**data)

json_data = """{
    "appid": "2309wfjwef",
    "channel": "retail",
    "person": {
        "fname": "John",
        "lname": "Doe"
        }
}"""

app_data = json.loads(json_data)

schema = AppSchema()
app = schema.load(app_data)

print(app.data.person.fname)