@synstack/json
Schema-safe and type-safe JSON serialization and deserialization
[!WARNING]
This package is included in the @synstack/synscript package. It is not recommended to install both packages at the same time.
[!NOTE]
This package is accessible through @synstack/fs for convenience.
What is it for?
When you need to work with JSON data in a type-safe way, this package provides simple, strongly-typed functions:
import { serialize, deserialize } from "@synstack/json";
import { z } from "zod";
const userSchema = z.object({
name: z.string(),
age: z.number(),
});
const jsonString = serialize(
{ name: "John", age: 30 },
{ schema: userSchema, pretty: true },
);
const user = deserialize(jsonString, { schema: userSchema });
console.log(user.name);
try {
deserialize("invalid json");
} catch (error) {
if (error instanceof JsonParseException) {
console.error("Failed to parse JSON:", error.message);
}
}
Installation
npm install @synstack/json
yarn add @synstack/json
pnpm add @synstack/json
Features
JSON Serialization
Convert JavaScript objects to JSON strings with optional pretty printing:
import { serialize } from "@synstack/json";
const json = serialize({ hello: "world" });
const prettyJson = serialize({ hello: "world" }, { pretty: true });
console.log(prettyJson);
Type-Safe Deserialization
Parse JSON strings with TypeScript type inference:
import { deserialize } from "@synstack/json";
const data = deserialize<{ count: number }>('{"count": 42}');
console.log(data.count);
try {
deserialize('{"invalid": json}');
} catch (error) {
console.error("Invalid JSON:", error.message);
}
Schema Validation
Use Zod schemas for runtime type checking:
import { serialize, deserialize } from "@synstack/json";
import { z } from "zod";
const configSchema = z.object({
port: z.number(),
host: z.string(),
debug: z.boolean(),
});
const jsonString = serialize(
{ port: 3000, host: "localhost", debug: true },
{ schema: configSchema },
);
const config = deserialize(jsonString, {
schema: configSchema,
});