如何使用棉花糖反序列化嵌套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)
答案 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)