【问题标题】:How to use JSON Schema to validate a JSON property of a sub-property with a random name如何使用 JSON Schema 验证具有随机名称的子属性的 JSON 属性
【发布时间】:2018-05-11 14:34:29
【问题描述】:

我想知道如何使用随机名称验证子属性中的“哈哈”?

{
  "shipping_address": {
      "randomName1":{
      "haha":"ddd"},
      "randomName2":{
      "haha":"ddd"},
      "randomName3":{
      "haha":"ddd"},
  }
}

我尝试过简单地使用 allOf,但我的不起作用:

{
  "$schema": "http://json-schema.org/draft-6/schema#",
  "type": "object",
  "properties": {
    "shipping_address": {
      "allOf": [
        { "properties":
          { "haha": { "type": "integer" } }
        }
      ]
    }
  }
}

你可以在这里试试:https://www.jsonschemavalidator.net/

【问题讨论】:

    标签: jsonschema json-schema-validator


    【解决方案1】:

    使用模式属性

     {
          "$schema": "http://json-schema.org/draft-6/schema#",
          "type": "object",
          "properties": {
            "shipping_address": {
              "patternProperties": {
                "^.*$": {          
                      "properties": {
                        "haha":{
                            "type":"integer"
                        }                    
                    }      
                }
              }
            }
          }
        }
    

    正如 vearutop 所说,改进后的版本:

    {
      "$schema": "http://json-schema.org/draft-6/schema#",
        "type": "object",
          "properties": {
            "shipping_address": {
              "additionalProperties":{
                "properties":{
                  "haha":{
                    "type":"integer"
                  }
                }
              }
            }
          }          
    }
    

    【讨论】:

    • 您可以使用"additionalProperties":{"properties":{"haha":{"type":"integer"}}},而不是使用patternProperties 作为随机名称,这样验证起来会更快
    猜你喜欢
    • 2020-06-18
    • 2015-11-09
    • 2020-06-14
    • 1970-01-01
    • 2018-03-25
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多