Spider
Spider

Reputation: 1470

How to use JSON Schema to validate a JSON property of a sub-property with a random name

I am wondering how could I validate the "haha" in a sub-property with a random name?

{
  "shipping_address": {
      "randomName1":{
      "haha":"ddd"},
      "randomName2":{
      "haha":"ddd"},
      "randomName3":{
      "haha":"ddd"},
  }
}

I have tried to simply use allOf, but mine does not work:

{
  "$schema": "http://json-schema.org/draft-6/schema#",
  "type": "object",
  "properties": {
    "shipping_address": {
      "allOf": [
        { "properties":
          { "haha": { "type": "integer" } }
        }
      ]
    }
  }
}

You can have a try here: https://www.jsonschemavalidator.net/

Upvotes: 1

Views: 225

Answers (1)

Spider
Spider

Reputation: 1470

Use patternProperties

 {
      "$schema": "http://json-schema.org/draft-6/schema#",
      "type": "object",
      "properties": {
        "shipping_address": {
          "patternProperties": {
            "^.*$": {          
                  "properties": {
                    "haha":{
                        "type":"integer"
                    }                    
                }      
            }
          }
        }
      }
    }

As vearutop commented, the improved version:

{
  "$schema": "http://json-schema.org/draft-6/schema#",
    "type": "object",
      "properties": {
        "shipping_address": {
          "additionalProperties":{
            "properties":{
              "haha":{
                "type":"integer"
              }
            }
          }
        }
      }          
}

Upvotes: 2

Related Questions