Zod实例序列化反序列化报错:寻求更优解析/序列化方案
问题:Zod序列化/反序列化astro:content引用类型报错
需求
- 创建Zod实例并序列化为JSON发送
- 接收JSON并解析回Zod实例
报错详情
ZodError: [ { "code": "invalid_type", "expected": "string", "received": "object", "path": [ 0, "parents", 0 ], "message": "Expected string, received object" },
临时解决方案
发送端
手动将所有引用字段从对象映射为ID字符串数组:
export async function GET() { const dbPersons = await getCollection("person"); const persons = dbPersons.map((dbPerson) => { // 直接返回dbPerson.data会触发上述错误 // return dbPerson.data; // 可行的临时处理逻辑 const parents = dbPerson.data.parents?.map(parent => parent.id); const children = dbPerson.data.children?.map(child => child.id); const spouses = dbPerson.data.spouses?.map(spouse => spouse.id); return Object.assign({}, { ...dbPerson.data, parents, children, spouses }); }); return new Response(JSON.stringify(persons)); }
接收端
const personAPIResp = await personsApi.json(); const persons = await ZPersonArray.parseAsync(personAPIResp);
关联的Schema定义
export const ZPerson = z.object({ id: z.number({ message: "Unique identifier of a person" }), // ... // 父母字段 parents: z.array(reference("person")).optional(), // ... });
疑问
是否存在更优解决方案?比如使用其他解析器或不同的序列化方式?
补充简化示例
config.ts
import { reference, z } from 'astro:content'; const ZPerson = z.object({ id: z.number({ message: "Unique identifier of a person" }), parents: z.array(reference("person")).optional(), }); export const ZPersonArray = z.array(ZPerson); export const collections = { person: ZPersonCollection }
content/1.yaml
id: 1 parents: ["2"]
content/2.yaml
id: 2
测试代码
import { getCollection } from 'astro:content'; let dbPersons = await getCollection("person"); const jsonPerson = JSON.stringify(dbPersons); const objectPerson = JSON.parse(jsonPerson); const persons = await ZPersonArray.parseAsync(objectPerson);
内容的提问来源于stack exchange,提问作者MortalFool
相关产品推荐
相关产品推荐

