python - jsonschema 去掉未知字段

标签 python json python-3.x jsonschema

有没有办法使用 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/additionalProperties

Message: 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/

相关文章:

python - 透明地将值分配给自定义数字类型

python - Plotly:如何以根样式绘制直方图,仅显示直方图的轮廓?

python - 如何找到多索引 DataFrame 的每个级别的最大绝对值

javascript - Ajax JSON 加载器不工作

JQuery $.ajax({}) - ajax 解析错误和 knockout

python-3.x - 无法使用从 git 安装的 pip 包

python - 检查列表中的单词并删除 pandas dataframe 列中的那些单词

python - 了解递归奇/偶函数

json - Loganalytics 工作区 ID 参数模板

python - 如何让pyttsx模块的语音变慢