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

如何用Zod从GitHub API返回数据中仅保留声明字段?

用Zod过滤未声明字段的方法

Zod默认解析时会保留所有额外字段,要只保留接口定义的字段,有几种程序化的解决方式:

  • 使用Zod内置的strip()方法
    这是最简洁的官方方案,在你的object schema上调用strip()后再执行解析,会自动移除所有未在schema中声明的字段。

示例代码:

import { z } from "zod";

// 定义带strip()的Repo Schema
const RepoSchema = z.object({
  id: z.number(),
  name: z.string(),
  full_name: z.string()
}).strip();

// 解析GitHub API返回的数据
const parsedRepo = RepoSchema.parse(githubApiResponse);
// 此时parsedRepo仅包含schema中定义的id、name、full_name字段
  • 给嵌套Schema也添加strip()
    如果你的Schema包含嵌套对象,要过滤嵌套结构里的额外字段,需要给每个嵌套的object schema也加上strip():
const OwnerSchema = z.object({
  login: z.string(),
  id: z.number()
}).strip();

const RepoSchema = z.object({
  id: z.number(),
  name: z.string(),
  owner: OwnerSchema
}).strip();

const parsedRepo = RepoSchema.parse(githubApiResponse);
// repo和其owner字段都会过滤掉未声明的额外字段
  • 手动提取字段(适用于不想修改原Schema的场景)
    如果已经有现成的Schema不想改动,可以在解析后手动提取需要的字段:
const RepoSchema = z.object({
  id: z.number(),
  name: z.string(),
  full_name: z.string()
});

const parsedRepo = RepoSchema.parse(githubApiResponse);
// 只保留接口定义的字段
const filteredRepo = {
  id: parsedRepo.id,
  name: parsedRepo.name,
  full_name: parsedRepo.full_name
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 13:18:00