How to create JSON Schema for Name/Value structure?

Damian Leszczyński - Vash picture Damian Leszczyński - Vash · Mar 6, 2014 · Viewed 18.1k times · Source

My problem is that i am serializing the content of map to JSON.

In the output (JSON), i have object that follow key/name syntax rule.

The key is created from map key, and the name from the value.

Model Example:

  class Storage {
       Map<String,String> values = new HashMap<>();

      {
         map.put("key1","key1");
         map.put("key2","key2");
         map.put("key3","key3");
      }

    }

JSON Example object:

{
  key1=value1,
  key2=value2,
  key3=value3
}

JSON Schema:

{
  "name": "storage",
  "description": "Store of key values",
  "properties": {
    // How can we describe the properties if we do not know the name ?
   }
}

The issue is that i do not know what the values will be but i know that they will be some.

Can you help me to provide me the full definition of schema?


Disclaimer:

I know that this can be also serialized as

 {
    values: [
       {key="key1", value="value1"},
       {key="key2", value="value2"},
       {key="key3", value="value3"}
    ]
 }

but is do not want to have array in the JSON.

Answer

McDowell picture McDowell · Mar 6, 2014

Assuming your validator supports it you can use patternProperties.

For the schema...

{
  "title": "Map<String,String>",
  "type": "object",
  "patternProperties": {
    ".{1,}": { "type": "string" }
  }
}

...and the document...

{
    "foo":"bar",
    "baz":1
}

...the value of property foo is valid because it is a string but baz fails validation because it is a number.