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

如何阻止Fastify移除JSON响应中的Null值?是否可配置/编程实现?

Fastify 空值响应的处理方案

Fastify 默认会自动移除响应对象中值为 undefined 的属性,这是它内置的 JSON 序列化行为。针对你的需求,有两种方向的解决办法:

关闭 undefined 属性移除特性

如果只是想保留 undefined 属性(但 null 仍会被保留为 null),可以在初始化 Fastify 实例时配置 jsonShorthand: false:

const fastify = require('fastify')({
  jsonShorthand: false
})

自动将 null/undefined 转为空数组

如果希望统一把 items 字段的 null/undefined 自动转为 [],更推荐用以下两种方式:

1. 全局自定义序列化器

通过全局配置序列化函数,批量处理所有响应的空值字段:

const fastify = require('fastify')()

fastify.setSerializerCompiler(() => {
  return (data) => {
    // 匹配 null 或 undefined
    if (data?.items == null) {
      data.items = []
    }
    return JSON.stringify(data)
  }
})

2. 响应钩子统一处理

利用 onSend 钩子在响应发送前修改 payload:

fastify.addHook('onSend', async (request, reply, payload) => {
  if (!payload) return payload
  const responseData = JSON.parse(payload)
  if (responseData?.items == null) {
    responseData.items = []
    return JSON.stringify(responseData)
  }
  return payload
})

3. 单个路由单独配置

如果只需要针对特定路由处理,可以在路由选项中单独设置序列化器:

fastify.get('/items/:id', {
  serializer: (data) => {
    if (data.items == null) {
      data.items = []
    }
    return JSON.stringify(data)
  }
}, async (request, reply) => {
  const { id } = request.params
  return { items: findItemById(id) }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 06:27:12