JSON模式:如何允许数值类型的属性使用空字符串


JSON schema: how to allow empty string for property with numeric type?

在属性定义中,我需要允许数值或空字符串值,这个表达式适合这个目的吗?

"tprice":{"type":["number",{"enum":[""]}]}

我用来验证数据的库(Jsv4)为空字符串生成错误:

Invalid type: string

而我尝试为这个属性设置零长度的字符串。

我认为您的解决方案是在模式中使用anyOf。这是适用于您的模式:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "properties": {
      "tprice": {
          "anyOf": [ 
          { 
              "type": "number"
          }, 
          { 
              "type": "string", 
              "maxLength": 0
          } 
       ] 
     }
  }
}

我已经用jsonschemalint.com测试过了。

{
   "tprice": 123
}

{
   "tprice": ""
}

验证很好。