Search code examples
javascriptjsonvalidationjavascript-objectsjsonschema

validate json object with varying properties


I have json object whose property values are unique and can be anything;

{
    "cat1": {
        "name": "kitty",
        "type": "animal",
        "color": "ginger"
    },
    "dog2": {
        "name": "ripple",
        "type": "animal",
        "color": "black"
    },
    "book10": {
        "name": "myBook",
        "type": "book",
        "color": "NA"
    },
    "orange6": {
        "name": "NA",
        "type": "fruit",
        "color": "orange"
    },
    "pig1":{
        "name": "spring",
        "type": "animal",
        "color": "pink"
    }
}

Now I'm confused how to write its validation schema. Does anybody know how to do it?

var mySchema = {
    "type": "object",
    "properties": {
         // no idea how to check varying properties like cat1, dog2, etc. which might change next time
    }
}


Solution

  • You can try this

    var mySchema = {
      "type": "object",
      "additionalProperties": {
        "type": "object",
        "properties": {
          "name": { "type": "string"},
          "type": { "type": "string"},
          "color": { "type": "string"},
        }
      }
    }
    
    

    ref: JSONSchema how to define a schema for a dynamic object