You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

不使用数组如何在JSON Schema中实现对象递归引用建模

问题原因

JSON Schema 规范本身完全支持对象类型的递归定义,不存在仅允许数组场景递归的限制,你遇到的栈溢出报错是 Fastify 内置的序列化工具 fast-json-stringify 早期版本对递归对象引用的处理逻辑不完善导致的。

修复方案

1. 优化Schema定义

将分类结构统一定义为递归类型,写法更规范也更容易被序列化工具识别:

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "$id": "https://www.example.com/schemas/food.json",
  "type": "object",
  "required": ["name", "category"],
  "properties": {
    "name": {
      "type": "string"
    },
    "category": {
      "$ref": "#/$defs/category"
    }
  },
  "$defs": {
    "category": {
      "type": ["object", "null"],
      "required": ["name"],
      "properties": {
        "name": {
          "type": "string"
        },
        "parent": {
          "$ref": "#/$defs/category"
        }
      }
    }
  }
}

2. 适配Fastify配置

  • 优先升级 Fastify 及相关依赖到最新稳定版,fast-json-stringify 从v3.x版本开始已经原生支持对象递归引用场景,升级后绝大多数情况可以直接解决栈溢出问题。
  • 如果受业务限制无法升级版本,可以给对应路由添加序列化配置开启循环引用支持:
fastify.get('/foods/:id', {
  schema: {
    response: {
      200: 上面定义的FoodSchema
    }
  },
  serializerOpts: {
    circular: true
  }
}, async (request, reply) => {
  // 业务逻辑
})
  • 如果是校验阶段报错,可以给 Fastify 的 AJV 校验器配置添加 strict: false 关闭严格模式即可。

内容的提问来源于stack exchange,提问作者Check12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 09:45:02