JSON Schema with unknown property names

ぃ、小莉子 提交于 2020-11-30 17:09:05

问题


I want to have a JSON Schema with unknown property names in an array of objects. A good example is the meta-data of a web page:

      "meta": {
        "type": "array",
        "items": {
          "type": "object",
          "properties": {
            "unknown-attribute-1": {
              "type": "string"
            },
            "unknown-attribute-2": {
              "type": "string"
            },
            ...
          }
        }
      }

Any ideas please, or other way to reach the same?


回答1:


Use patternProperties instead of properties. In the example below, the pattern match regex .* accepts any property name and I am allowing types of string or null only by using "additionalProperties": false.

  "patternProperties": {
    "^.*$": {
      "anyOf": [
        {"type": "string"},
        {"type": "null"}
      ]
    }
  },
  "additionalProperties": false



回答2:


You can make constraints on properties not explicitly defined. The following schema enforces "meta" to be an array of objects whose properties are of type string:

{
    "properties" : {
        "meta" : {
            "type" : "array",
            "items" : {
                "type" : "object",
                "additionalProperties" : {
                    "type" : "string"
                }
            }
        }
    }
}

In case you just want to have an array of strings, you may use the following schema:

{
    "properties" : {
        "meta" : {
            "type" : "array",
            "items" : {
                "type" : "string"
            }
        }
    }
}



回答3:


The Solution of @jruizaranguren works for me. Though I am the same who defines the schema, i choosed another solution

"meta": {
        "type": "array",
        "items": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "name": {
                "type": "string"
              },
              "value": {
                "type": "string"
              }
            }
          }
        }
      }

I converted the object to an array of name-value objects An example of a valid JSON:

"meta": [
    [
      {
        "name": "http-equiv",
        "value": "Content-Type"
      },
      {
        "name": "content",
        "value": "text/html; charset=UTF-8"
      }
    ],
    [
      {
        "name": "name",
        "value": "author"
      },
      {
        "name": "content",
        "value": "Astrid Florence Cassing"
      }
    ]
  ]


来源:https://stackoverflow.com/questions/32044761/json-schema-with-unknown-property-names

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!