JSON Schema 刚好有七种类型。不是四种,不是五种——七种。漏掉一种(尤其是 integer 或 null)会导致 schema 要么太宽松要么太死板。
七种类型
- string — 文本值:
"hello"、"2024-01-15"、"INV-001" - number — 任意数值,含小数:
42、3.14、-17.5 - integer — 仅限整数:
42、-7、0。3.14会被拒绝 - boolean — 只能是
true或false,没有别的 - array — 有序列表:
[1, 2, 3]。用items指定元素类型 - object — 键值结构:
{"name": "Alice", "age": 30}。用properties定义字段 - null — 显式的 null 值。不是”缺失”——是存在但为 null
number vs integer:重要的区分
number 同时接受整数和小数。integer 只接受整数。如果一个字段表示数量、计数或年龄——用 integer。如果表示价格、百分比或测量值——用 number。
没有 float 类型。没有 whole_numbers_only 标记。integer 类型就是整数限制。用 string 加正则来做数值校验,在有原生数值类型的情况下纯属多余。
null 是真实存在的类型
一个常见误解:null 不是 JSON Schema 类型,处理缺失靠省略字段就行。错了。null 是一等公民类型。JSON 显式支持 null 作为值,JSON Schema 在联合类型中使用它,比如 ["string", "null"] 表示可空字段——字段存在,但值是 null。
这对提取 schema 很重要。如果一个文档可能不包含保修期限,你希望模型返回 {"warranty_period": null}(明确表示”我看了,没有”),而不是编造一个值来填必填的 string 字段。
选对类型
发票提取 schema 的例子:
invoice_number→ string(文本标识符如 “INV-2024-001”)total_amount→ number(小数如 127.50)quantity→ integer(整数如 3)is_paid→ boolean(true/false)
全用 string 牺牲了类型安全,后续处理也更麻烦(得把 “127.50” 解析回数值)。该用 integer 的地方用了 number 会放过不该有的小数。每个字段都值得用最精确的类型。
一句话总结: JSON Schema 有 7 种类型——整数用 integer(不是 number),可空字段用 null(它是真实的类型),每个字段都应该选最精确的类型。