【发布时间】:2021-10-13 14:45:17
【问题描述】:
我正在解析一个文件并最终得到一个这样的字典:
user_data = {
"title": "TestA",
"sects": [
{
"type": "cmd",
"cmd0": {
"moveX": 12,
"moveY": 34,
"action": "fire"
},
"session": 9999,
"cmd1": {
"moveX": 56,
"moveY": 78,
"action": "stop"
},
"endType": 0,
},
{
"type": "addUsers",
"user1": {
"name": "John",
"city": "London"
},
"user2": {
"name": "Mary",
"city": "New York"
},
post = "yes"
}
]
}
我正在尝试使用 marshmallow 对其进行验证,但不确定如何处理这两件事:
- 对于
sects,每个嵌套字典的内容都依赖于type(cmd、addUser 等)。有没有办法根据字段的值来选择架构? - 是否有字段'startsWith'这样的东西来处理我可能有
cmd0、cmd1...cmdN的事实?
所以,类似于以下内容:
class CmdSchema(schema):
type = fields.Str()
cmdN = fields.Dict(...) # Allow cmd1, cmd2, etc
session = fields.Int()
endType = fields.Int()
class AddUsersSchema(schema):
type = fields.Str()
userN = fields.Dict(...) # Allow user1, user2, etc
post = fields.Str()
class ParsedFileSchema(schema):
title = fields.Str()
sects = fields.Nested(...) # Choose nested schema based on sects[i]['type']?
注意:我无法更改我正在解析的文件的格式/内容和顺序问题(因此我需要保留 cmd1、cmd2 等的顺序,以便它们能够以正确的顺序进行处理)。
【问题讨论】:
标签: python marshmallow