zod-json-patch
v0.0.1
Published
Generate type-safe Zod schemas for JSON Patch operations.
Readme
zod-json-patch
Generate type-safe Zod 4 schemas for RFC 6902 JSON Patch operations.
Install
bun add zod-json-patch zod
API
createPatchSchema(schema) returns a Zod schema for patches against schema.
PatchOperations<Schema> provides the inferred patch operation type.
Objects and arrays
import { applyPatch } from "fast-json-patch";
import { z } from "zod";
import { createPatchSchema } from "zod-json-patch";
const objectSchema = z.object({
name: z.string(),
tags: z.array(z.string()),
});
const operationsSchema = createPatchSchema(objectSchema);
const operations = operationsSchema.parse([
{ op: "replace", path: "/name", value: "Ada" },
{ op: "remove", path: "/tags/0" },
{ op: "add", path: "/tags/-", value: "science" },
]);
const document = applyPatch({ name: "Grace", tags: ["logic"] }, operations).newDocument;Null and optional fields
null is a value. undefined represents an optional field, which allows add and remove operations.
const objectSchema = z.object({
middleName: z.string().nullable(),
nickname: z.string().optional(),
});
const operationsSchema = createPatchSchema(objectSchema);
const operations = operationsSchema.parse([
{ op: "replace", path: "/middleName", value: null },
{ op: "add", path: "/nickname", value: "Amazing Grace" },
]);Applying patches
fast-json-patch is recommended for applying validated operations, but you can use any RFC 6902-compatible library.
