gpt4 book ai didi

c# - 如何使用 JSON Schema 将字符串值验证为 json 文本中的数字?

转载 作者:行者123 更新时间:2023-12-02 14:53:23 32 4
gpt4 key购买 nike

我希望能够将答案字段验证为数值。下面的片段是一个答案,它是一个更大的答案词典的一部分。每个答案都遵循通用格式,因此需要答案字段为字符串类型。

            "1": {
"answer": "80035",
"web_validated": true,
"web_error_string": "",
"server_error_string": ""
},

这会产生一个问题,因为我们正在使用 JSON 模式来验证答案字典。我们需要将答案字段验证为数值,这是由字典必须遵循的 JSON 模板确定的。以下是字典中一个问题的上述答案的模板片段。

      {
"id": "1",
"text": "KFI Number (Null required check)",
"type": "text",
"source": "phoebus",
"kfid_mapping": "KFID000",
"kfid_mapping_value": "",
"valid_answers": null,
"display_online": "readonly",
"required": "1",
"display_internal": "yes",
"hints": null,
"logic": null,
"rules": null,
"reason": null,
"conditional_explanation": null,
"conditional_question_id": null,
"conditional_question_answered": null,
"enabled": "1",
"order": "2",
"fk_section_id": "1",
"validated": false
}

我们用于验证问题 ID 的当前 JSON 架构:1。

"definitions": {
"question1-1": {
"type": "object",
"properties": {
"answer": {
"type": "string",
"minLength": 1
}
}
//other definitions removed
}
}

以上是此问题中显示的答案的 JSON 模式定义。

可能的解决方案:

  1. 将答案字段转换为数字字段,即去掉“” - 这个确实有效,但它更昂贵,而且是一个 hack。所以预在验证之前处理。
  2. 只需将答案字段验证为字符串,即不为空、不为空和最小长度检查。

我想看看 JSON Schema 是否可行?

最佳答案

正如其他人提到的,您可以使用模式。这是添加到示例中的语法:

"definitions": {
"question1-1": {
"type": "object",
"properties": {
"answer": {
"type": "string",
"pattern": "^\d+$",
"description": "Use regex to validate this string as a series of one or more digits"
}
}
//other definitions removed
}
}

关于c# - 如何使用 JSON Schema 将字符串值验证为 json 文本中的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54346248/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com