如何第一时间看到新文章?
收藏本博客列表页,并在首页与工具聚合页留意指南入口。阅读文章无需注册或邮件订阅。
通过可直接使用的示例掌握必填字段、嵌套对象、数组、枚举、可复用定义和条件校验,建立清晰可维护的数据契约。
JSON Schema 用来描述 JSON 数据的结构与约束。它可以作为 API 契约、配置文件规范和导入校验规则,把“status 必须存在”这类口头约定变成可执行规则。下面的示例采用现代 JSON Schema 写法,并保持足够小,方便直接修改。
下面的 Schema 要求根节点是对象,并且必须包含非空字符串 id 和指定范围内的 status。
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["id", "status"],
"properties": {
"id": { "type": "string", "minLength": 1 },
"status": { "enum": ["pending", "active", "disabled"] }
},
"additionalProperties": false
}additionalProperties: false 可以捕获拼写错误和意外字段,但应有意识地使用。它适合受控配置和内部接口;公共 API 如果需要向后兼容,可能要允许新增字段。
嵌套结构的规则应放在对应属性内部。下面要求 address 存在,并继续校验其内部字段。
{
"type": "object",
"required": ["name", "address"],
"properties": {
"name": { "type": "string" },
"address": {
"type": "object",
"required": ["country", "postalCode"],
"properties": {
"country": { "type": "string", "minLength": 2 },
"postalCode": { "type": "string", "pattern": "^[A-Za-z0-9 -]+$" }
},
"additionalProperties": false
}
}
}正则表达式只能验证文本形式,不能证明邮编真实存在。涉及国家、库存、权限等业务事实时,应由业务代码继续校验。
items 描述每个数组元素,minItems 和 uniqueItems 控制数组整体。
{
"type": "array",
"minItems": 1,
"uniqueItems": true,
"items": {
"type": "object",
"required": ["sku", "quantity"],
"properties": {
"sku": { "type": "string", "minLength": 1 },
"quantity": { "type": "integer", "minimum": 1 }
},
"additionalProperties": false
}
}uniqueItems 比较完整 JSON 值。两个对象即使 sku 相同,只要数量不同仍会被视为不同;若要按某个字段唯一,通常需要应用代码或数据库约束。
$defs 复用定义重复结构应只有一个事实来源。把定义放入 $defs,再通过 $ref 引用。
{
"$defs": {
"money": {
"type": "object",
"required": ["amount", "currency"],
"properties": {
"amount": { "type": "number", "minimum": 0 },
"currency": { "type": "string", "pattern": "^[A-Z]{3}$" }
},
"additionalProperties": false
}
},
"type": "object",
"properties": {
"subtotal": { "$ref": "#/$defs/money" },
"total": { "$ref": "#/$defs/money" }
}
}财务系统还应明确小数表示方式。需要精确计算时,可以使用经过校验的十进制字符串或最小货币单位整数。
当一个字段决定其他字段是否必填时,可以使用 if、then 和 else。
{
"type": "object",
"required": ["deliveryMethod"],
"properties": {
"deliveryMethod": { "enum": ["pickup", "shipping"] },
"shippingAddress": { "type": "string", "minLength": 1 },
"pickupLocationId": { "type": "string", "minLength": 1 }
},
"allOf": [
{
"if": { "properties": { "deliveryMethod": { "const": "shipping" } } },
"then": { "required": ["shippingAddress"] },
"else": { "required": ["pickupLocationId"] }
}
]
}条件规则应保持可读。如果 Schema 开始承担完整工作流、权限或库存逻辑,应把这些规则移回应用层。
致力于为开发者提供最佳的 JSON 处理工具
更多文章即将发布...
返回博客关于跟进更新、选题方向与互动反馈。
收藏本博客列表页,并在首页与工具聚合页留意指南入口。阅读文章无需注册或邮件订阅。
围绕 JSON 校验、格式化、转换与调试流程,以及 JSON Work 工具更新,与在线工具的本地能力一一对应。
可以。请通过关于页的联系方式或 GitHub 反馈;我们会优先安排贴近真实开发场景的教程。