Home > Back-end >  How to use arbitrary property names in a JSON Schema
How to use arbitrary property names in a JSON Schema

Time:06-25

I'm working with JSON data where one portion of it is a key-value pair collection, where the key is an arbitrary string and the value is an array of strings. I'm trying to write a schema for this, but I'm not sure how to represent arbitrary property names. So for an object like this:

{
  "K1": ["V1", "V2", "V3"],
  "K2": ["V4", "V5"],
  "K3": ["V6", "V7"]
}

What would be the right way to write a JSON schema with the following requirements:

  • There must be at least one property.
  • Properties can have any arbitrary string for their name
  • Every property's associated value must be an array of strings
  • Every string array must contain at least one string (ie. must not be empty)

CodePudding user response:

You can express a restricted pattern for a property or set of properties with patternProperties; its value is a schema, which is evaluated against the values of all properties that match. So for example, to express a set of rules used for properties that start with a capital letter, you can do "patternProperties": { "^[A-Z]": { ... more rules here .... To define the rules for a property name in terms of a full schema, you can use propertyNames.

To express a schema for the value of all properties, regardless of name, you can use additionalProperties. These rules will not match against any property already matched with a properties or patternProperties.

You can express the minimum number of properties with minProperties.

You can express the rules for all items in an array with items. And minItems can be used to express the minimum allowable number of items.

The schema for your data can be expressed by:

{
  "type": "object",
  "minProperties": 1,
  "additionalProperties": {
    "type": "array",
    "minItems": 1,
    "items": {
      "type": "string"
    }
  }
}

https://json-schema.org/understanding-json-schema/reference/object.html
https://json-schema.org/understanding-json-schema/reference/array.html

  • Related