A runtime JSON schema validation library for MoonBit, inspired by Zod and Pydantic
Dependencies
š äøęē README
| Document | Description |
|---|---|
| Design Document | Important! Core architecture, design decisions, and future directions |
| API Reference | Detailed API documentation |
| CLI Reference | Command-line usage |
| Benchmark | Performance comparison with other validation libraries |
| Examples | Practical usage examples |
| Exporters | moon_zod exporters documentation |
| Importers | moon_zod importers documentation |
moon add Betterlol/moon_zodimport {
"Betterlol/moon_zod",
}let schema = @moon_zod.object({
"name": @moon_zod.string().min(2).max(50),
"age": @moon_zod.number().int().min(0).max(150),
"email": @moon_zod.string().email(),
})
match schema.parse(input_json) {
Ok(valid) => {
println("Valid")
println(@debug.to_string(valid))
}
Err(errors) => {
println("Invalid")
println(errors.length().to_string())
for e in errors {
println(e.to_string())
}
}
}# Infer schema from sample, validate data
moon run cmd/validate -- '{"name":"Alice","age":30}' '{"name":"Bob","age":25}'
# PASS
# Batch validation with JSON Lines
moon run cmd/validate -- '{"name":"Alice"}' '{"name":"Bob"}\n{"name":"Eve"}'
# Results: 2 passed, 0 failed| Feature | moon_zod | Typical Validation |
|---|---|---|
| Error collection | Collects all errors in one pass | Most libs fail-fast on first error |
| Hallucination defense | Default Strip mode silently removes unknown fields | Would pass through hallucinated data |
| Named schema export | schema_to_prompt_named() generates modular TypeScript interfaces with type name references | Inline expansion + duplication |
| JSON Schema export | to_json_schema() generates standard schema for LLM API | Manual schema maintenance |
| Path precision | Every error includes exact field path (users[0].profile.age) | Often just a flat message |
| Wasm-ready | Mutable path stack ā zero heap allocation on success path | String-heavy allocation per parse |
moon_zod/
āāā core/ # Core schema validation library
ā āāā types.mbt # ValidationError, SchemaResult, core types
ā āāā schema.mbt # Schema struct, parse dispatch, path stack
ā āāā string.mbt # string() factory + validators (trim, to_lower, to_upper)
ā āāā number.mbt # number() factory + validators
ā āāā boolean.mbt # boolean() factory
ā āāā null.mbt # null() factory
ā āāā bigint.mbt # bigint() factory
ā āāā any_unknown.mbt # any() / unknown() pass-through schemas
ā āāā array.mbt # array() factory + parse_array
ā āāā tuple.mbt # tuple() factory + parse_tuple
ā āāā object.mbt # object() + modes (strip/passthrough/strict), pick/omit/partial/extend/merge
ā āāā optional.mbt # optional() factory
ā āāā default.mbt # default() factory
ā āāā enum.mbt # enum_values() factory
ā āāā literal.mbt # literal() factory (constant values)
ā āāā union.mbt # union() factory
ā āāā intersection.mbt # intersection() / intersect()
ā āāā refine.mbt # refine() for custom validation
ā āāā transform.mbt # transform() for data transformation
ā āāā preprocess.mbt # preprocess() for input preprocessing
ā āāā shared_utils.mbt # Common utilities (unwrap_schema, peel_optional, etc.)
ā āāā constraint_extractor.mbt # Extract constraint info from rules
ā āāā moon_zod_wbtest.mbt # White-box tests (path stack invariants)
ā
āāā combinators/ # Schema combinator utilities
ā āāā schema_combinators.mbt # Schema composition helpers
ā
āāā exporters/ # Code/schema export tools
ā āāā prompt.mbt # schema_to_prompt() / schema_to_prompt_named()
ā āāā prompt_renderer.mbt # Trait-based prompt rendering
ā āāā json_schema.mbt # to_json_schema() / to_json_schema_named()
ā āāā json_schema_renderer.mbt # Trait-based JSON Schema rendering
ā āāā moonbit_struct.mbt # schema_to_moonbit_struct() + static to_schema() generation
ā āāā schema_exporter.mbt # Shared exporter utilities
ā
āāā importers/ # Schema import tools
ā āāā from_json_schema.mbt # json_schema_to_moon_zod() ā reverse JSON Schema ā moon_zod code generation
ā
āāā tests/ # Test suite (466 tests)
ā āāā test_string.mbt # string() validator tests (trim, to_lower, to_upper, nonempty)
ā āāā test_number.mbt # number() validator tests
ā āāā test_boolean_null.mbt # boolean/null tests
ā āāā test_object.mbt # object() mode + pick/omit/partial/extend/merge tests
ā āāā test_array.mbt # array() + nonempty tests
ā āāā test_tuple.mbt # tuple() tests
ā āāā test_combinators.mbt # union/literal/optional/default/brand/bigint tests
ā āāā test_any_unknown_preprocess.mbt # any/unknown/preprocess tests
ā āāā test_transform_refine.mbt # transform/refine tests
ā āāā test_json_schema.mbt # JSON Schema export + $defs/$ref tests
ā āāā test_json_schema_fixes.mbt # exclusiveMin/Max semantics + enum edge cases
ā āāā test_moonbit_struct.mbt # MoonBit struct generation tests
ā āāā test_prompt.mbt # Prompt generation tests
ā āāā test_prompt_named.mbt # Named schema export tests
ā āāā test_custom_message.mbt # Custom error message tests
ā āāā test_errors.mbt # Error collection tests
ā āāā test_schema_to_code.mbt # Code generation tests
ā āāā reexporter.mbt # Test re-exports
ā
āāā cmd/ # CLI tools
ā āāā main/ # Benchmark runner (performance baselines)
ā āāā wasm/ # WebAssembly cross-language benchmark
ā āāā json2schema/ # JSON ā moon_zod schema code generator + JSON Schema reverse importer
ā āāā gen-struct/ # JSON Schema ā MoonBit struct generator
ā āāā validate/ # JSON schema validator (infer-then-validate)
ā
āāā examples/ # LLM agent demonstrations
āāā gen-struct/ # JSON Schema ā MoonBit struct generator demo
āāā json2schema/ # JSON ā moon_zod schema code generation
āāā mock/ # Mock agent demonstrations
ā āāā llm_agent/ # Basic LLM tool calling example
ā āāā educational_agent/ # Multi-round self-correction demo
āāā multiple_schemas/ # Handling multiple schemas
āāā real_llm_agent/ # Real LLM integration (with API fallback to mock)
āāā resources/ # Sample data files (JSON, JSON Schema)
āāā schema2json/ # Schema ā JSON Schema export demo
āāā schema2prompt/ # Schema ā prompt generation showcase
āāā shared_schemas/ # Shared schema definitions (library package)
āāā validate_cli/ # CLI validation demo# Testing & Building
moon test # Run all tests (466 total, 0 warnings)
moon build # Build the library
moon check # Type check (0 errors, 0 warnings)
moon info && moon fmt # Update interface + format
# CLI Tools
moon run cmd/main # Run performance benchmarks
moon run cmd/json2schema -- '{"hello":"world"}' # JSON ā moon_zod schema code
moon run cmd/json2schema -- --from-json-schema '<{...}>' # JSON Schema ā moon_zod code
moon run cmd/json2schema -- --from-json-schema '<{...}>' --verbose # with debug output
moon run cmd/gen-struct -- --schema '<{...}>' # JSON Schema ā MoonBit structs
moon run cmd/validate -- '{"name":"Alice"}' '{"name":"Bob"}' # Validate JSON
# Examples
moon run examples/mock/llm_agent # Basic LLM tool calling demo
moon run examples/mock/educational_agent # Multi-round self-correction demo
moon run examples/real_llm_agent -- product prompt # Real LLM with mock fallback
moon run examples/real_llm_agent -- product validate # Validate with real API
moon run examples/multiple_schemas # Multiple schema handling
moon run examples/schema2json -- product schema # Schema ā JSON Schema export
moon run examples/schema2prompt -- product schema # Schema ā prompt generation showcase
moon run examples/json2schema # JSON ā moon_zod schema code genwebsite: extension.
fn escape_ident(name : String) -> Stringfn escape_mbt_string(s : String) -> Stringfn escape_variable_name(name : String) -> Stringfn format_double_simple(v : Double) -> Stringlet schema = @moon_zod.literal(Json::string("hello"))
schema.parse(Json::string("hello")) // Ok
schema.parse(Json::string("world")) // Errlet schema = @moon_zod.string().min(3).describe("username")
let code = schema_to_moon_zod_code(schema)
// "@moon_zod.string().min(3).describe(\"username\")"let named_list = schema_to_moon_zod_code_named(root_schema, None)
// Returns:
// "User: @moon_zod.object({ ... }).name(\"User\")\n
// Profile: @moon_zod.object({ ... }).name(\"Profile\")"A runtime JSON schema validation library for MoonBit, inspired by Zod and Pydantic
Dependencies