How to define JSON Schema for Map<String, Integer>?

32,753

Solution 1

You can:

{
  "type": "object",
  "properties": {
    "itemType": {"$ref": "#/definitions/mapInt"},
    "itemCount": {"$ref": "#/definitions/mapInt"}
  },
  "definitions": {
    "mapInt": {
      "type": "object",
      "additionalProperties": {"type": "integer"}
    }
  }
}

Solution 2

The question is kind of badly described, let me see if I can rephrase it and also answer it.

Question: How to Represent a map in json schema like so Map<String, Something>

Answer:

It looks like you can use Additional Properties to express it https://json-schema.org/understanding-json-schema/reference/object.html#additional-properties

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

For example let's say you want a Map<string, string>

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

Or something more complex like a Map<string, SomeStruct>

{
  "type": "object",
  "additionalProperties": { 
    "type": "object",
    "properties": {
      "name": "stack overflow"
    }
  }
}
Share:
32,753

Related videos on Youtube

Newbie
Author by

Newbie

Updated on February 24, 2022

Comments

  • Newbie
    Newbie about 2 years

    I have a json :

    {
    "itemTypes": {"food":22,"electrical":2},
    "itemCounts":{"NA":211}
    }
    

    Here the itemTypes and itemCounts will be common but not the values inside them (food, NA, electrical) which will be keep changing but the will be in the format : Map<String, Integer>

    How do I define Json Schema for such generic structure ?

    I tried :

    "itemCounts":{
          "type": "object"
        "additionalProperties": {"string", "integer"}
    
        }
    
    • Trevor Bye
      Trevor Bye over 7 years
      By defining the json shcema, are you asking how to write a class that represents the json?
    • Newbie
      Newbie over 7 years
      @J.West No Schema in the form of JSON
    • Winter Soldier
      Winter Soldier over 7 years
      Is this the example you want to refer to?
  • Sachin Jain
    Sachin Jain about 6 years
    How do we specify which of the two should be treated as "key" here ?
  • Jared Forsyth
    Jared Forsyth over 5 years
    Keys will always be strings in JSON. both itemType and itemCount in this example are maps of "string" to "integer". Also note that you don't have to use the definitions thing in order to make a map of string to int -- that's just a shortcut used in this example to deduplicate definitions.
  • ttugates
    ttugates over 4 years
    I am searching for how to represent Map<number, number>. I control server and client and thus serializers, but can't figure out how to define the key as a number, any help?
  • Brendan Samek
    Brendan Samek over 4 years
    @ttugates You won't be able to do that in JSON schema since it's that doesn't conform to the JSON specification
  • charlag
    charlag almost 2 years
    This defines an array of pairs, not a map