有没有办法使用 jsonschema 根据模式验证 json 并从 json 中删除未知的键?
架构示例:
{
"type":"object",
"$schema": "http://json-schema.org/draft-03/schema",
"required":False,
"properties":{
"address": {
"type":"object",
"required":True,
"properties":{
"city": {
"type":"string",
"required":True
}
},
"phoneNumber": {
"type":"array",
"required":False,
"items":
{
"type":"object",
"required":False,
"properties":{
"number": {
"type":"string",
"required":False
}
}
}
}
}
}
示例数据:
{
"address":{
"streetAddress": "1 Street",
"city":"New York",
"name": "Tom",
"houseNumber":18
},
"phoneNumber":[
{
"type":"home",
"number":"212 222 2222"
}
]
}
因此验证器应该传递数据并返回剥离的版本,如下所示:
{
"address":{
"city":"New York",
},
"phoneNumber":[
{
"number":"212 222 2222"
}
]
}
Cerberus 确实有“purge_unknown”功能,但它不支持 JSON-Schema。
最佳答案
我注意到您可以根据验证错误过滤掉未知字段。在这种情况下,您可以使用 additionalProperties
字段来限制意外的键。
{
"type":"object",
"$schema": "http://json-schema.org/draft-03/schema",
"required":false,
"properties":{
"address": {
"type":"object",
"required":true,
"properties":{
"city": {
"type":"string",
"required":true
}
},
"additionalProperties": false,
},
"phoneNumber": {
"type":"array",
"required":false,
"items":
{
"type":"object",
"required":false,
"properties":{
"number": {
"type":"string",
"required":false
}
},
"additionalProperties": false,
}
}
}
}
这是给定示例输入的验证结果:
Message: Property 'streetAddress' has not been defined and the schema does not allow additional properties.
Schema path: #/properties/address/additionalPropertiesMessage: Property 'name' has not been defined and the schema does not allow additional properties. Schema path: #/properties/address/additionalProperties
Message: Property 'houseNumber' has not been defined and the schema does not allow additional properties. Schema path: #/properties/address/additionalProperties
Message: Property 'type' has not been defined and the schema does not allow additional properties. Schema path: #/properties/phoneNumber/items/additionalProperties
关于python - jsonschema 去掉未知字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57367655/