简体   繁体   中英

How to define an object with a veriable name in JSON Schema?

I want to create a JSON schema for this JSON "pseudo-code" example:

{
    "xyz": {
        "$something": {
            "property_a": "...",
            "property_b": "...",
            "property_c": "..."
        }
    }
}

$something can be one of the following strings: foo , bar , or buz . My current schema looks like this:

{
  "xyz": {
    "id": "xyz",
    "type": "object",
    "properties": {
      "foo": {
        "id": "foo",
        "type": "object",
        "additionalProperties": false,
        "required": ["property_a"],
        "properties": {
          "property_a": {
            "id": "property_a",
            "type": "string"
          },
          "property_b": {
            "id": "property_b",
            "type": "string"
          },
          "property_c": {
            "id": "property_a",
            "type": "string"
          }
        }
      },
      "bar": {
        ... copy&paste foo
      },
      "buz": {
        ... copy&paste foo
      }
    }
  }
}

It's working, but it's a lot duplicated code. So I'm looking for a more elegant way for implementing it.

How to define a list of values (lie enum ) allowed as name for a property in JSON Schema?

patternProperties works like properties, except the keys of the object are regular expressions.

https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.5.5

An example from the Understanding JSON Schema site

{
  "type": "object",
  "patternProperties": {
    "^S_": { "type": "string" },
    "^I_": { "type": "integer" }
  },
  "additionalProperties": false
}

In this example, any additional properties whose names start with the prefix S_ must be strings, and any with the prefix I_ must be integers. Any properties explicitly defined in the properties keyword are also accepted, and any additional properties that do not match either regular expression are forbidden.

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