Skip to content

Schema to JSON Schema

Schema.toJsonSchemaDocument derives the canonical JSON codec for a schema and exports its encoded side as JSON Schema. Export is best-effort documentation and interop—keep runtime validation at the boundary. Plain builders follow the call rules.

Exporting a document

const Depot = Schema.Struct({
  name: Schema.String,
  capacity: Schema.Finite
})
 
function depotDocument() {
  return Schema.toJsonSchemaDocument(Depot)
}
// Run in an effect function:
//   const document = depotDocument()
//   try Console.log(document.dialect)
//   try Console.log(try Effect.try(() => JSON.stringify(document.schema)))
draft-2020-12
{"type":"object","properties":{"name":{"type":"string"},"capacity":{"type":"number"}},"required":["name","capacity"],"additionalProperties":true}

The returned document contains dialect (default "draft-2020-12"), schema, and definitions. By default, additionalProperties is true even though runtime decoding strips excess keys unless onExcessProperty: "error" is set.

Canonical representations and drafts

function alternateDrafts() {
  const document = Schema.toJsonSchemaDocument(
    Schema.Tuple([Schema.String, Schema.FiniteFromString])
  )
  const draft07 = JsonSchema.toDocumentDraft07(document)
  const draft04 = JsonSchema.toDocumentDraft04(document)
  return { draft07, draft04 }
}
// Run in an effect function: try Console.log(try Effect.try(() => JSON.stringify(alternateDrafts())))
{"draft07":{"dialect":"draft-07","schema":{"type":"array","maxItems":2,"minItems":2,"items":[{"type":"string"},{"type":"string"}]},"definitions":{}},"draft04":{"dialect":"draft-04","schema":{"type":"array","maxItems":2,"minItems":2,"items":[{"type":"string"},{"type":"string"}]},"definitions":{}}}

Because export describes toCodecJson's encoded side, FiniteFromString exports as { "type": "string" } and custom toCodecJson hooks govern both runtime JSON and exported JSON Schema. Convert to older drafts with JsonSchema.toDocumentDraft07 or toDocumentDraft04.

Encoded-side metadata

const DepotName = Schema.Trim.pipe(Schema.annotateEncoded({
  title: "Depot input",
  description: "Text entered before surrounding whitespace is removed",
  examples: [" north "],
  default: "central",
  "x-widget": "depot-picker"
}))
 
function nameDocument() {
  return Schema.toJsonSchemaDocument(DepotName, {
    includeAnnotationKey: (key) => key.startsWith("x-")
  })
}
// Run in an effect function: try Console.log(try Effect.try(() => JSON.stringify(nameDocument().schema)))
{"type":"string","title":"Depot input","description":"Text entered before surrounding whitespace is removed","default":"central","examples":[" north "],"x-widget":"depot-picker"}

Use Schema.annotateEncoded for wire-facing metadata. Standard JSON Schema keywords (title, description, default, examples, readOnly, writeOnly, format, contentEncoding, contentMediaType, contentSchema) are exported automatically; use includeAnnotationKey to opt in custom keys.

Constraints and optional fields

const DepotRequest = Schema.Struct({
  code: Schema.String.check(Schema.isPattern(/^[A-Z]{2}[0-9]{3}$/u)),
  note: Schema.optionalKey(Schema.String),
  alias: Schema.optional(Schema.String),
  capacity: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 120 }))
})
 
function requestDocument() {
  return Schema.toJsonSchemaDocument(DepotRequest)
}
// Run in an effect function: try Console.log(try Effect.try(() => JSON.stringify(requestDocument().schema)))
{"type":"object","properties":{"code":{"type":"string","pattern":"^[A-Z]{2}[0-9]{3}$"},"note":{"type":"string"},"alias":{"anyOf":[{"type":"string"},{"type":"null"}]},"capacity":{"type":"integer","minimum":1,"maximum":120}},"required":["code","capacity"],"additionalProperties":true}
  • optionalKey omits the field from required; optional also permits undefined, which canonical JSON maps to null.
  • isPattern exports pattern only with the u flag (and no flags other than d, g, y); add a toJsonSchema annotation to override.
  • JavaScript counts UTF-16 code units while JSON Schema counts Unicode code points, so string length bounds export conservatively (e.g., isMinLength(3) may emit minLength: 2).

Recursive definitions

interface DepotTree {
  name: string
  branches: ReadonlyArray<DepotTree>
}
const DepotTree = Schema.Struct({
  name: Schema.String,
  branches: Schema.Array(Schema.suspend((): Schema.Codec<DepotTree> => DepotTree))
}).annotate({ identifier: "DepotTree" })
 
function treeDocument() {
  return Schema.toJsonSchemaDocument(DepotTree)
}
// Run in an effect function: try Console.log(try Effect.try(() => JSON.stringify(treeDocument())))
{"dialect":"draft-2020-12","schema":{"$ref":"#/$defs/DepotTree"},"definitions":{"DepotTree":{"type":"object","properties":{"name":{"type":"string"},"branches":{"type":"array","items":{"$ref":"#/$defs/DepotTree"}}},"required":["name","branches"],"additionalProperties":true}}}

Annotate recursive or shared schemas with a unique identifier to emit stable #/$defs/<name> references (otherwise the exporter generates names such as Objects_). Never reuse one identifier for different shapes.

Generation options

function strictDocument() {
  return Schema.toJsonSchemaDocument(DepotRequest, {
    onExcessProperty: "error",
    generateDescriptions: true,
    includeAnnotationKey: (key) => key.startsWith("x-")
  })
}
// Run in an effect function: try Console.log(try Effect.try(() => JSON.stringify(strictDocument().schema)))
{"type":"object","properties":{"code":{"type":"string","pattern":"^[A-Z]{2}[0-9]{3}$","description":"a string matching the RegExp ^[A-Z]{2}[0-9]{3}$"},"note":{"type":"string"},"alias":{"anyOf":[{"type":"string"},{"type":"null"}]},"capacity":{"type":"integer","minimum":-9007199254740991,"maximum":9007199254740991,"description":"an integer","allOf":[{"minimum":1,"maximum":120,"description":"a value between 1 and 120"}]}},"required":["code","capacity"],"additionalProperties":false}
  • onExcessProperty: "error": emits additionalProperties: false when expressible (match with the same runtime parse option).
  • generateDescriptions: true: fills missing check descriptions from expected.
  • referencePolicy: controls $defs allocation over canonical JSON ASTs.

JSON string codecs

const DepotText = Schema.fromJsonString(Depot)
 
function jsonTextDocument() {
  return Schema.toJsonSchemaDocument(DepotText)
}
// Run in an effect function: try Console.log(try Effect.try(() => JSON.stringify(jsonTextDocument().schema)))
{"type":"string","contentMediaType":"application/json","contentSchema":{"type":"object","properties":{"name":{"type":"string"},"capacity":{"type":"number"}},"required":["name","capacity"],"additionalProperties":true}}

Schema.fromJsonString exports a string schema with contentMediaType: "application/json" and contentSchema set to the inner schema's JSON representation.


The matching Effect page: effect.website/docs/v4/schema/json-schema