{"id":20029177,"url":"https://github.com/jsonjoy-com/json-type","last_synced_at":"2026-01-20T05:35:24.513Z","repository":{"id":257812447,"uuid":"868466301","full_name":"jsonjoy-com/json-type","owner":"jsonjoy-com","description":"JSON Type implementation. Fast JSON data type schema validation with JIT compilation.","archived":false,"fork":false,"pushed_at":"2025-09-04T12:28:28.000Z","size":5181,"stargazers_count":2,"open_issues_count":6,"forks_count":1,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-12-01T12:35:11.759Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jsonjoy-com.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"github":"streamich"}},"created_at":"2024-10-06T13:06:34.000Z","updated_at":"2025-09-04T12:27:30.000Z","dependencies_parsed_at":null,"dependency_job_id":"e2f05517-7ee9-43ad-a0d1-01bdfb4b80cf","html_url":"https://github.com/jsonjoy-com/json-type","commit_stats":null,"previous_names":["jsonjoy-com/json-type"],"tags_count":18,"template":false,"template_full_name":null,"purl":"pkg:github/jsonjoy-com/json-type","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jsonjoy-com%2Fjson-type","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jsonjoy-com%2Fjson-type/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jsonjoy-com%2Fjson-type/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jsonjoy-com%2Fjson-type/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jsonjoy-com","download_url":"https://codeload.github.com/jsonjoy-com/json-type/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jsonjoy-com%2Fjson-type/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28596493,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-20T02:08:49.799Z","status":"ssl_error","status_checked_at":"2026-01-20T02:08:44.148Z","response_time":117,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-13T09:18:47.205Z","updated_at":"2026-01-20T05:35:24.507Z","avatar_url":"https://github.com/jsonjoy-com.png","language":"TypeScript","funding_links":["https://github.com/sponsors/streamich"],"categories":[],"sub_categories":[],"readme":"# JSON Type\n\nModern type system for JSON. JSON Type is way a new way to specify JSON schema,\nit is an alternative and improvement over JSON Schema and JSON Type Definition.\n\nFeatures of the library:\n\n- JIT compilation for schema validator.\n- JIT compilation for JSON (text) serializer.\n- JIT compilation for CBOR, MessagePack, and JSON (binary) serializers.\n- JIT compilation for safe serialization size estimation.\n- Schema export and import.\n- Const types.\n- Union type discriminator is specified using the [JSON Expression](https://jsonjoy.com/specs/json-expression) language.\n- Some discriminators are automatically inferred, when const types are used.\n- Custom validation rules can be added using the JSON Expression language.\n- Can generate random JSON values that match the schema.\n\n## Quick Start\n\nDefine a user schema and validate data in just a few lines:\n\n```ts\nimport {t} from '@jsonjoy.com/json-type';\n\n// Define a user type\nconst User = t.object({\n  id: t.num,\n  name: t.str,\n  email: t.str,\n}).optional({\n  age: t.num.gte(0).lte(120),\n});\n\n// Validate data\nconst isValid = User.validateSchema();\nUser.validate({\n  id: 1,\n  name: \"Alice\",\n  email: \"alice@example.com\",\n  age: 30\n}); // ✅ Valid\n\n// Generate random test data\nconst randomUser = User.random();\n// { id: 42, name: \"xyz123\", email: \"abc\", age: 25 }\n```\n\n## Advanced Features\n\nJSON Type goes beyond basic validation with powerful JIT compilation:\n\n```ts\n// Compile ultra-fast validators\nconst validator = User.compileValidator({errors: 'boolean'});\nconst isValid = validator(userData); // Blazing fast validation\n\n// Generate TypeScript types\nconst tsCode = User.toTypeScript();\n// type User = { id: number; name: string; email: string; age?: number; }\n\n// Compile optimized serializers\nconst toJson = User.compileEncoder('json');\nconst jsonString = toJson(userData); // Faster than JSON.stringify\n\nconst toCbor = User.compileCborEncoder();\nconst cborBytes = toCbor(userData); // Binary serialization\n```\n\n## Real-World Example\n\nBuild type-safe APIs with complex schemas:\n\n```ts\nimport {t} from '@jsonjoy.com/json-type';\n\n// Define API request/response types\nconst CreatePostRequest = t.object({\n  title: t.str.options({min: 1, max: 100}),\n  content: t.str.options({min: 10}),\n  tags: t.array(t.str).options({max: 5}),\n  published: t.bool,\n});\n\nconst Post = t.object({\n  id: t.str,\n  title: t.str,\n  content: t.str,\n  tags: t.array(t.str),\n  published: t.bool,\n  createdAt: t.num.options({format: 'u64'}),\n  author: t.object({\n    id: t.str,\n    name: t.str,\n  }),\n});\n\nconst CreatePostResponse = t.object({\n  success: t.bool,\n  post: Post,\n}).optional({\n  error: t.str,\n});\n\n// Extract TypeScript types using t.infer\ntype PostType = t.infer\u003ctypeof Post\u003e;\ntype CreateRequestType = t.infer\u003ctypeof CreatePostRequest\u003e;\ntype CreateResponseType = t.infer\u003ctypeof CreatePostResponse\u003e;\n\n// Now you have full type safety!\nconst newPost: PostType = {\n  id: \"123\",\n  title: \"My Blog Post\",\n  content: \"This is the content...\",\n  tags: [\"typescript\", \"json\"],\n  published: true,\n  createdAt: Date.now(),\n  author: {\n    id: \"user456\",\n    name: \"John Doe\"\n  }\n};\n```\n\n## Usage\n\nType builder for JSON-like data structures:\n\n```ts\nimport {t} from '@jsonjoy.com/json-type';\n\nt.String(); // { kind: 'str' }\nt.String({const: 'add'}); // { kind: 'str', const: 'add' }\n\nconst type = t.Object([\n  t.Field(\n    'collection',\n    t.Object([\n      t.Field('id', t.String({format: 'ascii', noJsonEscape: true})),\n      t.Field('ts', t.num, {format: 'u64'}),\n      t.Field('cid', t.String({format: 'ascii', noJsonEscape: true})),\n      t.Field('prid', t.String({format: 'ascii', noJsonEscape: true})),\n      t.Field('slug', t.String({format: 'ascii', noJsonEscape: true})),\n      t.Field('name', t.str, {isOptional: true}),\n      t.Field('src', t.str, {isOptional: true}),\n      t.Field('doc', t.str, {isOptional: true}),\n      t.Field('authz', t.str, {isOptional: true}),\n      t.Field('active', t.bool),\n    ]),\n  ),\n  t.Field(\n    'block',\n    t.Object([\n      t.Field('id', t.String({format: 'ascii', noJsonEscape: true})),\n      t.Field('ts', t.num, {format: 'u64'}),\n      t.Field('cid', t.String({format: 'ascii', noJsonEscape: true})),\n      t.Field('slug', t.String({format: 'ascii', noJsonEscape: true})),\n    ]),\n  ),\n]);\n```\n\n## Node Types\n\nJSON Type provides a comprehensive set of node types for modeling JSON-like data structures. Each node type has a `kind` property that identifies its type, along with specific properties and constraints.\n\n### Core Types\n\n#### AnySchema (`any`)\nRepresents data of unknown type.\n\n```ts\ninterface AnySchema {\n  kind: 'any';\n  validator?: string | string[];  // Custom validation rules\n  metadata?: Record\u003cstring, unknown\u003e;  // Custom metadata\n}\n```\n\n**Example:**\n```ts\ns.Any()  // { kind: 'any' }\n```\n\n#### BooleanSchema (`bool`)\nRepresents a JSON boolean value.\n\n```ts\ninterface BooleanSchema {\n  kind: 'bool';\n  validator?: string | string[];  // Custom validation rules\n}\n```\n\n**Example:**\n```ts\ns.Boolean()  // { kind: 'bool' }\n```\n\n#### NumberSchema (`num`)\nRepresents a JSON number with optional format and range constraints.\n\n```ts\ninterface NumberSchema {\n  kind: 'num';\n  format?: 'i' | 'u' | 'f' | 'i8' | 'i16' | 'i32' | 'i64' | 'u8' | 'u16' | 'u32' | 'u64' | 'f32' | 'f64';\n  gt?: number;      // Greater than (exclusive)\n  gte?: number;     // Greater than or equal to\n  lt?: number;      // Less than (exclusive)\n  lte?: number;     // Less than or equal to\n  validator?: string | string[];\n}\n```\n\n**Format options:**\n- `i*` - Signed integers (i8, i16, i32, i64)\n- `u*` - Unsigned integers (u8, u16, u32, u64)\n- `f*` - Floating point (f32, f64)\n\n**Examples:**\n```ts\ns.Number()                           // { kind: 'num' }\ns.Number({format: 'u32'})           // 32-bit unsigned integer\ns.Number({gte: 0, lte: 100})        // Number between 0 and 100\n```\n\n#### StringSchema (`str`)\nRepresents a JSON string with optional format and length constraints.\n\n```ts\ninterface StringSchema {\n  kind: 'str';\n  format?: 'ascii' | 'utf8';        // Character encoding format\n  ascii?: boolean;                   // @deprecated Use format: 'ascii'\n  noJsonEscape?: boolean;            // Skip JSON escaping for performance\n  min?: number;                      // Minimum length\n  max?: number;                      // Maximum length\n  validator?: string | string[];\n}\n```\n\n**Examples:**\n```ts\ns.String()                                    // { kind: 'str' }\ns.String({format: 'ascii'})                  // ASCII-only string\ns.String({min: 1, max: 50})                  // String with length constraints\ns.String({format: 'ascii', noJsonEscape: true})  // Optimized ASCII string\n```\n\n#### BinarySchema (`bin`)\nRepresents binary data with an encoded type.\n\n```ts\ninterface BinarySchema {\n  kind: 'bin';\n  type: TType;                       // Type of value encoded in binary\n  format?: 'json' | 'cbor' | 'msgpack' | 'resp3' | 'ion' | 'bson' | 'ubjson' | 'bencode';\n  min?: number;                      // Minimum size in bytes\n  max?: number;                      // Maximum size in bytes\n  validator?: string | string[];\n}\n```\n\n**Examples:**\n```ts\ns.Binary(s.String())                         // Binary-encoded string\ns.Binary(s.Object(), {format: 'cbor'})      // CBOR-encoded object\n```\n\n### Composite Types\n\n#### ArraySchema (`arr`)\nRepresents a JSON array with elements of a specific type.\n\n```ts\ninterface ArraySchema {\n  kind: 'arr';\n  type: TType;                       // Type of array elements\n  min?: number;                      // Minimum number of elements\n  max?: number;                      // Maximum number of elements\n  validator?: string | string[];\n}\n```\n\n**Examples:**\n```ts\ns.Array(s.String())                  // Array of strings\ns.Array(s.Number(), {min: 1, max: 10})  // Array with 1-10 numbers\n```\n\n#### TupleSchema (`tup`)\nRepresents a fixed-length array with specific types for each position.\n\n```ts\ninterface TupleSchema {\n  kind: 'tup';\n  types: TType[];                    // Types for each position\n  validator?: string | string[];\n}\n```\n\n**Example:**\n```ts\ns.Tuple(s.String(), s.Number(), s.Boolean())  // [string, number, boolean]\n```\n\n#### ObjectSchema (`obj`)\nRepresents a JSON object with defined fields.\n\n```ts\ninterface ObjectSchema {\n  kind: 'obj';\n  keys: ObjectKeydSchema[];       // Defined object keys\n  decodeUnknownKeys?: boolean;\n  encodeUnknownKeys?: boolean;\n  validator?: string | string[];\n}\n```\n\n**Examples:**\n```ts\ns.Object([\n  s.prop('name', s.String()),\n  s.propOpt('age', s.Number())       // Optional field\n])\n```\n\n#### ObjectKeySchema (`key`)\nRepresents a single field in an object.\n\n```ts\ninterface ObjectKeydSchema {\n  kind: 'key';\n  key: string;                       // Field name\n  type: TType;                       // Field value type\n  optional?: boolean;                // Whether field is optional\n}\n```\n\n**Examples:**\n```ts\ns.prop('id', s.String())             // Required field\ns.propOpt('description', s.String()) // Optional field\n```\n\n#### MapSchema (`map`)\nRepresents an object treated as a map with string keys and uniform value types.\n\n```ts\ninterface MapSchema {\n  kind: 'map';\n  type: TType;                       // Type of all values\n  validator?: string | string[];\n}\n```\n\n**Example:**\n```ts\ns.Map(s.Number())                    // Object with number values\n```\n\n### Advanced Types\n\n#### ConstSchema (`const`)\nRepresents a constant value.\n\n```ts\ninterface ConstSchema {\n  kind: 'const';\n  value: any;                        // The constant value\n  validator?: string | string[];\n}\n```\n\n**Examples:**\n```ts\ns.Const('hello' as const)            // Constant string\ns.Const(42 as const)                 // Constant number\ns.Const(null)                        // Null constant\n```\n\n#### RefSchema (`ref`)\nReferences another type by ID.\n\n```ts\ninterface RefSchema {\n  kind: 'ref';\n  ref: string;                       // ID of referenced type\n}\n```\n\n**Example:**\n```ts\ns.Ref('UserType')                    // Reference to type with ID 'UserType'\n```\n\n#### OrSchema (`or`)\nRepresents a union type (one of multiple possible types).\n\n```ts\ninterface OrSchema {\n  kind: 'or';\n  types: TType[];                    // Possible types\n  discriminator: Expr;               // Expression to determine type\n}\n```\n\n**Example:**\n```ts\ns.Or(s.String(), s.Number())         // String or number\n```\n\n#### FunctionSchema (`fn`)\nRepresents a function type with request and response.\n\n```ts\ninterface FunctionSchema {\n  kind: 'fn';\n  req: TType;                        // Request type\n  res: TType;                        // Response type\n}\n```\n\n**Example:**\n```ts\ns.Function(s.String(), s.Number())   // Function: string -\u003e number\n```\n\n#### FunctionStreamingSchema (`fn$`)\nRepresents a streaming function type.\n\n```ts\ninterface FunctionStreamingSchema {\n  kind: 'fn$';\n  req: TType;                        // Request stream type\n  res: TType;                        // Response stream type\n}\n```\n\n**Example:**\n```ts\ns.Function$(s.String(), s.Number())  // Streaming function\n```\n\n### Common Properties\n\nAll node types extend the base `TType` interface with these common properties:\n\n```ts\ninterface TType {\n  kind: string;                      // Node type identifier\n\n  // Display properties\n  title?: string;                    // Human-readable title\n  intro?: string;                    // Short description\n  description?: string;              // Long description (may include Markdown)\n\n  // Metadata\n  id?: string;                       // Unique identifier\n  meta?: Record\u003cstring, unknown\u003e;    // Custom metadata\n  examples?: TExample[];             // Usage examples\n\n  // Deprecation\n  deprecated?: {\n    description?: string;            // Deprecation reason and alternative\n  };\n}\n```\n\n### Validation\n\nMany types support custom validation through the `validator` property:\n\n```ts\n// Single validator\n{ validator: 'email' }\n\n// Multiple validators\n{ validator: ['required', 'email'] }\n```\n\nValidation rules are applied using the JSON Expression language for flexible custom constraints.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjsonjoy-com%2Fjson-type","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjsonjoy-com%2Fjson-type","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjsonjoy-com%2Fjson-type/lists"}