如何验证json schema中的属性字段是否为UUID?

juud5qan  于 2023-07-01  发布在  其他
关注(0)|答案(3)|浏览(162)
{
  "status": 200,
  "id": "123e4567-e89b-12d3-a456-426655440000",
  "shop": {
    "c73bcdcc-2669-4bf6-81d3-e4ae73fb11fd": {
      "123e4567-e89b-12d3-a456-426655443210": {
        "quantity": {
          "value": 10
        }
      },
      "123e4567-e89b-12d3-a456-426655443211": {
        "quantity": {
          "value": 20
        }
      }
    }
  }
}

这是我的JSON响应。我想验证字段“c73 bcdcc-2669- 4 bf 6 - 81 d3-e4 ae 73 fb 11 fd”、“123 e4567-e89 b-12 d3-a456-426655443210”和“123 e4567-e89 b-12 d3-a456-426655443211”,这些字段在每次访问端点时都是唯一生成的。

klr1opcd

klr1opcd1#

基于@pxcv7r的回答:
为了验证UUID,您可以使用JSON模式中的format,它提供了对UUID语法的内置支持:{“type”:“string”,“format”:“uuid”}
参见https://json-schema.org/understanding-json-schema/reference/string.html
此外,您可以使用"propertyNames""unevaluatedProperties"的组合来避免任何正则表达式的需要:

{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "type": "object",
  "properties": {
    "status": {
      "type": "integer"
    },
    "id": {
      "type": "string",
      "format": "uuid"
    },
    "shop": {
      "type": "object",
      "minProperties": 1,
      "maxProperties": 1,
      "propertyNames": {
        "format": "uuid"
      },
      "unevaluatedProperties": {
        "type":"object",
        "minProperties": 1,
        "propertyNames": {
          "format": "uuid"
        },
        "unevaluatedProperties": {
          "title": "single variant of a shop",
          "type": "object",
          "properties": {
            "quantity": {
              "type": "object",
              "properties": {
                "value": {
                  "type": "integer"
                }
              }
            }
          }
        }
      }
    }
  }
}
8ljdwjyq

8ljdwjyq2#

要在JSON模式中验证字符串是否符合正则表达式模式,请使用{ "type": "string", "pattern": "\b[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}\b" }
具体模式改编自问题Searching for UUIDs in text with regex,更多细节请参见此处。
为了验证UUID,您可以在JSON模式中使用format,它提供了对UUID语法的内置支持:{ "type": "string", "format": "uuid" }
参见https://json-schema.org/understanding-json-schema/reference/string.html

goqiplq2

goqiplq23#

你需要“patternProperties”:

{ 
  "$schema":"http://json-schema.org/draft-07/schema#",
  "type":"object",
  "properties": {
    "shop":{
      "type":"object",
      "additionalProperties":false,
      "patternProperties":{
        "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}": {
          "type":"object",
          "patternProperties" :{
            "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}":{
              "type":"object",
               "properties":{
                 "quantity":{
                   "type":"object",
                   "properties":{
                     "value":{
                       "type":"integer"
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

相关问题