programing

알 수 없는 속성 이름을 가진 JSON 스키마

newnotes 2023. 3. 1. 11:29
반응형

알 수 없는 속성 이름을 가진 JSON 스키마

개체 배열에 알 수 없는 속성 이름을 가진 JSON 스키마를 갖고 싶습니다.좋은 예는 웹 페이지의 메타 데이터입니다.

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

다른 방법이 없을까요? 아니면 다른 방법이 없을까요?

사용하다patternProperties대신properties다음 예제에서는 패턴이 regex와 일치합니다..*모든 속성 이름을 받아들이며 타입을 허용합니다.string또는null사용만으로"additionalProperties": false.

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

... 또는 (원래 질문에서와 같이) "개체"에 문자열을 허용하려는 경우:

  "patternProperties": {
    "^.*$": {
        {"type": "string"},
    }
  },
  "additionalProperties": false

명시적으로 정의되지 않은 속성에 대한 제약을 설정할 수 있습니다.다음 스키마는 "meta"를 속성이 문자열 유형인 개체의 배열로 강제합니다.

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

문자열 배열만 원하는 경우 다음 스키마를 사용할 수 있습니다.

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

@jruizaranguren의 솔루션이 효과가 있습니다.스키마를 정의하는 것은 동일하지만 다른 솔루션을 선택했습니다.

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

개체를 이름 값 개체의 배열로 변환했습니다. 유효한 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"
      }
    ]
  ]

언급URL : https://stackoverflow.com/questions/32044761/json-schema-with-unknown-property-names

반응형