簡體   English   中英

json-schema 中有沒有辦法驗證匹配正則表達式的對象鍵?

[英]Is there a way in json-schema to validate object keys matching regex?

有沒有辦法讓 json 模式驗證器來驗證 json 對象的 例如:

{
    "$schema": "http://json-schema.org/draft-07/schema",
    "type": "object",
    "properties": { // here properties is an object containing user-defined keys that should be alphanumeric or underscore.
        "values": {
            "type": "object",
            "patternProperties": {
                "[a-zA-Z0-9_]+": {
                    "description": "Foo"
                }
            }
        }
    }
}

所以這里有一些應該和不應該通過的例子:

// Should pass:
{
 "values": {
   "myKey1": { "foo": 1 },
   "myKey2_": "bar"
 }
}

// Should fail but no error is shown saying this doesnt match schema:
{
  "values": {
    "m\1[]": 123
  }
}

我嘗試使用patternProperties但任何與我的正則表達式不匹配的東西都被忽略了,沒有在違規行上拋出驗證錯誤。 這與關於 patternProperties 的文檔一致: https ://json-schema.org/understanding-json-schema/reference/object.html#pattern-properties

有沒有辦法做我正在尋找的東西? 謝謝

您應該能夠使用additionalProperties使不傳遞所需的patternProperties的對象無效。

默認情況下,允許任何其他屬性。

{
"$schema": "http://json-schema.org/draft-07/schema",
"type": "object",
"properties": {
    "values": {
        "type": "object",
        "patternProperties": {
            "[a-zA-Z0-9_]+": {
                "description": "Foo"
            },
            "additionalProperties": false
            }
        }
    }
}

JSON 模式:附加屬性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM