【问题标题】:how to validate JSON schema of return type String| undefined using typescript如何验证返回类型字符串的 JSON 模式|使用打字稿未定义
【发布时间】:2018-10-18 13:12:09
【问题描述】:

我的 JSON 响应的两种变体是:

{
  firstName: "abc",
  LastName: "xyz",
  Address: "abc123"
}

{
  firstName: undefined,
  LastName: undefined,
  Address: undefined
}

即使将 JSON Schema 定义为:

var ResponseSchema = {
  "firstName": {
    "type": [String,undefined],
  },
  "LastName": {
    "type": [String,undefined],
  },
  "Address": {
    "type": [String,undefined],
  },
  "required": [
    "firstName",
    "LastName",
    "Address",
  ],
}

响应对象:

{
  firstName: undefined,
  LastName: undefined,
  Address: undefined
}

得到一个错误:

需要属性“firstName”
需要属性“姓氏”
需要属性“地址”

使用“jsonschema”节点包。

【问题讨论】:

    标签: typescript jsonschema


    【解决方案1】:

    首先:在架构中使用正确的类型名称(字符串)

    您想编写 JSON 模式。根据定义,您的type 可以是字符串或字符串数​​组。你要做的是传入一个 TypeScript 类型定义,而不是一个字符串。

    试试

      "firstName": {
        "type": ["string", "null"],
      },
      "LastName": {
        "type": ["string", "null"],
      },
      "Address": {
        "type": ["string","null"],
      },
      "required": [
        "firstName",
        "LastName",
        "Address",
      ]
    

    第二:undefined 不是 JSON 架构的有效类型

    将属性设置为undefined 被视为未设置该属性。对于这种情况,我建议您转到null

    【讨论】:

    • undefined 不是 JSON Schema 中的类型,因为它不是 JSON 中的类型。
    【解决方案2】:

    我不知道 jsonschema,但您的定义和必填字段在我看来是某种概念错误。

    你定义

    "required": [
      "firstName", 
      "LastName", 
      "Address"
    ]
    

    但是将每个字段的类型设置为String,undefined。如果您现在将它们设置为undefined,则不满足要求。

    换句话说:jsonschema 似乎有效,因为它会为您的响应抛出该错误:

    {
      "firstname": undefined,
      "Lastname": undefined,
      "Address": undefined,
    }
    

    【讨论】:

      【解决方案3】:

      null 是 JSON 中的有效类型,JSON Schema 中也是如此。

      我不知道 typescript,但这里以 JSON Schema 为例。

      {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "a": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "required": [
          "a"
        ]
      }
      

      作为 JSON 实例,这将通过验证:

      {
        "a": null
      }
      

      【讨论】:

        猜你喜欢
        • 2021-08-20
        • 2021-08-01
        • 2021-10-22
        • 1970-01-01
        • 2021-12-13
        • 1970-01-01
        • 1970-01-01
        • 2021-08-10
        • 2019-09-08
        相关资源
        最近更新 更多