简体   繁体   中英

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

Is there a way to have the json schema validator to validate keys of a json object? For example:

{
    "$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"
                }
            }
        }
    }
}

So here's some examples of what should and shouldn't pass:

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

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

I tried using patternProperties but anything that doesn't match my regex is just ignored, no validation error is thrown on the offending line. This is consistent with documentation on patternProperties: https://json-schema.org/understanding-json-schema/reference/object.html#pattern-properties

Is there a way to do what i'm looking for? Thanks

You should be able to use additionalProperties to make an object invalid that doesn't pass the patternProperties you've required.

By default any additional properties are allowed.

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

JSON Schema : Additional Properties

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM