验证具有不同属性的 json 对象

问题描述

我有一个 json 对象,它的属性值是唯一的,可以是任何东西;

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

现在我很困惑如何编写其验证模式。有人知道怎么做吗?

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

解决方法

你可以试试这个

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

参考:JSONSchema how to define a schema for a dynamic object