如何为Map <String,Integer>定义JSON模式?

New*_*bie 11 schema json jsonschema geojson json-schema-validator

我有一个json:

{
"itemType": {"food":22,"electrical":2},
"itemCount":{"NA":211}
}
Run Code Online (Sandbox Code Playgroud)

这里的itemType和itemCount将是常见的,但不是它们内部的值(食物,NA,电子),它们将不断变化,但将采用以下格式:地图

如何为这种通用结构定义Json Schema?

我试过了 :

"itemCount":{
      "type": "object"
    "additionalProperties": {"string", "integer"}

    }
Run Code Online (Sandbox Code Playgroud)

esp*_*esp 16

您可以:

{
  "type": "object",
  "properties": {
    "itemType": {"$ref": "#/definitions/mapInt"},
    "itemCount": {"$ref": "#/definitions/mapInt"}
  },
  "definitions": {
    "mapInt": {
      "type": "object",
      "additionalProperties": {"type": "integer"}
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • JSON 中的键始终是“字符串”。此示例中的“itemType”和“itemCount”都是“字符串”到“整数”的映射。另请注意,您不必使用“定义”来创建字符串到 int 的映射 - 这只是本示例中用于删除重复定义的快捷方式。 (2认同)

fra*_*ant 6

这个问题描述得不太好,让我看看是否可以改写并回答它。

问题:如何像这样在 json 模式中表示地图Map<String, Something>

回答:

看起来你可以用Additional Properties它来表达它https://json-schema.org/understanding-json-schema/reference/object.html#additional-properties

{
  "type": "object",
  "additionalProperties": { "type": "something" }
}

Run Code Online (Sandbox Code Playgroud)

例如,假设您想要一个Map<string, string>

{
  "type": "object",
  "additionalProperties": { "type": "string" }
}
Run Code Online (Sandbox Code Playgroud)

或者更复杂的东西,比如Map<string, SomeStruct>

{
  "type": "object",
  "additionalProperties": { 
    "type": "object",
    "properties": {
      "name": "stack overflow"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)