eclipsesource/play-json-schema-validator

Don't care about the key, but what type its value should be

Closed this issue · 5 comments

Hey there,

not sure where to look for the answer so I'm posting it here.
I need to validate a JSON object that can contain any key name, but its value should be of type "string".
So basically I don't care about the key or how many keys I can have, but I must specify that the correspondent value should be a string.

Is there any way to specify that?

Thanks!

Hi,
if I understood you correctly you want to have an object that can contain arbitrary properties but at least one of them (or all?) have to be of type string?

Hi Edgar,

Thanks for the reply.
That is exactly what I'm looking for.
Just to give you an idea:

In this json, the parameters property is an object that can contain any property name (0 or more) but the type of the property must be string for all of them.

{
   "parameters":{
        "propertie1":"value1",
        "propertie2":"value2"
   }
}

For this other example, the edges properties is an array of objects where it must have only one property and the type must be an array of any string

"edges":[
   {"A":["B"]},
   {"B":["C","D","E"]},
   {"D":["F","C"]}
]

Thanks!

I think both cases can be solved by using patternProperties, here's some example code for the first example:

val schema = JsonSource.schemaFromString(
      """{
        |  "properties": {
        |    "parameters": {
        |      "patternProperties": {
        |        ".*": {"type": "string"}
        |      }
        |    }
        |  }
        |}""".stripMargin).get

SchemaValidator.validate(schema,
  Json.obj(
    "parameters" -> Json.obj(
      "param1" -> "bar",
      "param2" -> "foo"
    )
  )
).isSuccess must beTrue

SchemaValidator.validate(schema,
  Json.obj(
    "parameters" -> Json.obj(
      "param1" -> 3,
      "param2" -> "foo"
    )
  )
).isError must beTrue

Your second example is a little bit more complex, but the following schema should cover that use case as well.

{
  "properties": {
    "edges": {
      "items": {
        "patternProperties": {
          ".*": {
            "type": "array",
            "items": { "type": "string" }
          }
        },
        "maxProperties": 1
      }
    }
  }
}

Does this answer your question?

Cool!

That works perfectly.
Thank you very much!
I did not know about the patternProperties.

This is an awesome library. Thank you for open sourcing it.

Regards

Glad I could help, if there's anything else, let me know.