10

How do i define key value pairs object in json schema (the "correct" way) ?

i want to define this:

"id" : 99,
_info : {
    "name" : "somename",
    "href" : "someUrl"
}

Are any of the following two accurate?:

1)

{
    "type": "object",
    "name": "MyObj",
    "properties": {
        "id": {
            "type": "integer"
        },
        "_info": {
            "type": "array",
            "items": {
                "type": "object"
                "properties": {
                    "key": {
                        "type": "string",
                        "description": "key"
                    },
                    "value": {
                        "type": "string",
                        "description": "the value"
                    }
                }
            }
        }
    }
}

2)

{
    "type": "object",
    "name": "MyObj",
    "properties": {
        "id": {
            "type": "integer",
        "_info": {
            "type": "object",
            "additionalProperties": {
                "type": "string",
                "description": "string values"
            }
        }
    }
}

What is the correct way to get this accomplished and people will know what the schema is and the object will look like when serialized/deserialized?

Gustavo
  • 685
  • 3
  • 7
  • 17

1 Answers1

16

In JSON an object is already a collection of key-value pairs. You don't need anything special in order to define it:

{
    "_info":{"type":"object"}
}

From here you can add constraints.

  • If you know the name of the keys, you add them to "properties"
  • If you know all possible keys, you set "additionalProperties" to false
  • If you want to restrict the possible key names, you use "patternProperties".

Update 2019/09/10

As suggested in comments, if you want to restrict all properties to be of type string, you may do it this way:

{
  "title": "Force every property to have a string value",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "additionalProperties": {"type": "string"}
}
jruizaranguren
  • 12,679
  • 7
  • 55
  • 73
  • 6
    Well, but this doesn't restrict values to being strings. Looking at Gustavo's schema attempts, it looks like that's what he wanted... – tpei Jan 07 '16 at 11:06
  • 1
    @tpei, I have modified the answer to cover your concern. – jruizaranguren Sep 10 '19 at 06:49
  • This is fantastic. Didn't know `additionalProperties` could take in an object. A lot more complex solutions are suggested in other answers on this site. – belvederef May 07 '20 at 11:24
  • just to add this for reference: https://json-schema.org/understanding-json-schema/reference/object.html – gai-jin Feb 09 '23 at 12:52