Skip to content

Conversation

Sachinkry
Copy link

Implements the z.jsonString() schema primitive for validating and parsing JSON strings, addressing issue #4646.

Basic JSON Syntax Validation

const schema = z.jsonString();
schema.parse('{"name": "Alice", "age": 30}'); // ✅ returns original string
schema.parse("invalid json"); // ❌ throws error

JSON Parsing with Schema Validation

const userSchema = z.jsonString(z.object({
  name: z.string(),
  age: z.number(),
}));
userSchema.parse('{"name": "Alice", "age": 30}'); // ✅ returns { name: "Alice", age: 30 }

Details

  • Implement z.jsonString() to validate JSON strings and optionally parse+validate against an inner schema.
  • Adds core $ZodJSONString, public APIs (classic/mini), and pipe-based parsing to inner schemas.
  • Emits invalid_format on JSON syntax errors; returns original string when no inner schema is provided.
  • Includes focused tests (10) and documentation updates (API + v4 changelog).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant