Universe

gairm-import on Typst Universe Latest GitHub release version of gairm-import GitHub Actions build workflow status on the gairm-import main branch MIT license badge linking to the gairm-import LICENSE file Number of GitHub stargazers for gairm-import

JSON Schema → Typst dict coercer.
Validate a JSON document against a JSON Schema (draft 7 subset) and get back a normalised Typst value ready to render. Bring your own schema, such as JSON Resume's.

"gairm" is Irish for vocation. The package was originally a JSON Resume loader.

Contents

What it is

gairm-import checks a JSON document against a schema and returns it as Typst values. Every problem in the document is reported at once, each with its path and, for a misspelt key, a “Did you mean …?” hint. The schema can be a JSON Schema document or one you build with Typst functions, and you can edit either with lenses before use. Requires Typst 0.15.0 or later.

Quick start

Translate a JSON Schema document you already have:

#import "@preview/gairm-import:0.13.0": parse, schema-from-json-schema

#let book-schema = schema-from-json-schema(json("book-schema.json"))
#let book = parse(path("book.json"), schema: book-schema)

Or build the schema in Typst:

#import "@preview/gairm-import:0.13.0": (
  parse, object, array-of, string, number,
)

#let book-schema = object((
  title:  string(),
  author: string(),
  year:   number(),
  tags:   array-of(string()),
))

#let book = parse(path("book.json"), schema: book-schema)

The translator takes a draft 7 subset and panics on anything it cannot honour rather than dropping it; REFERENCE.md lists the keywords it supports and how it differs from draft 7.

With this book.json:

{
  "title": "The Pocket Atlas of Imaginary Places",
  "author": "Aoife Brennan",
  "year": 1998,
  "tags": ["atlas", "fiction"]
}

the result mirrors the document: book.title is a string, book.year a number and book.tags an array of strings.

API at a glance

Group Names
Run parse, validate, coerce, format-errors
Schemas schema-from-json-schema
Constructors string, number, integer, array-of, object, map, any-of, one-of, not-of, if-of, nullable, enum-of, const-of
Constants content-type, bool-type, null-type, any-type
Edit lens-get, lens-put, lens-over, add-field, remove-field, set-required, unset-required
Inspect describe-schema, paths-of-kind
Pointers path-to-pointer, pointer-to-path

parse validates and coerces in one call and panics with every problem found. validate returns the problems as a list, and coerce builds the model without checking. All three take schema: and strict-null: (default false). REFERENCE.md covers the rest, one section per group.

Deprecated, working until 1.0: resume-schema and resume-schema-strict (see Validating a JSON Resume), leaving out schema: (it defaults to resume-schema, and is required in 1.0), str-type, number-type, integer-type, the nine format constants (date-string … time-string), pattern-string, lens, lens-then, kind-at, the lens-first argument order (lens-get(at, schema)), the (kind: "lens", path: …) shape, a kind name string in paths-of-kind, and hand-built nodes of the old kind names ("str", "pattern-string", "date-string" …). REFERENCE.md gives the replacement for each.

Input forms

parse, validate and coerce take the document, or where to read it:

You pass It is read as
path("resume.json") JSON, resolved from your file
bytes, such as read("resume.json", encoding: none) JSON
a dictionary, such as json("resume.json") the document itself
any other value: an array, a number, a string the document itself, whatever root the schema takes

A string is data, not a path: inside a package it would resolve from the package, never your file, so a .json-looking string the schema rejects panics with a hint to use path(..). A null document panics. schema-from-json-schema takes the first three forms only.

Errors

parse reports every problem in one panic. A document with a numeric basics.email and two stray keys, parsed with the stricter resume-schema-strict from Validating a JSON Resume:

error: panicked with: gairm-import: found 3 problems in the input:
  - basics.email: expected string, got integer.
  - work[0].positon: unknown key "positon". Did you mean "position"?
  - meta.foo: unknown key "foo". Valid keys: canonical, version, lastModified.

The plain resume-schema reports only the first line, since upstream lets undeclared keys through. To present problems yourself, call validate, which returns them as records. The first line above is (path: ("basics", "email"), code: "type", message: "expected string, got integer.", expected: "string", got: "integer").

Branch on code, not on the message. expected and got hold the data behind the message, or none where a code has nothing to put there:

code Meaning expected got
type Wrong JSON type (also: an enum or union none of whose members takes that type) The type name(s) The value’s type name
required A required key is missing
unknown-key A key the object does not declare The valid keys The key
dependent A key required by another key’s presence is missing The missing key The key that requires it
enum Not one of the enum’s values The values The value
format Not in the format’s shape (date, email, …) The format’s description The value
pattern Does not match the pattern The pattern’s description The value
length String too short or too long The bound broken: (min-length: 3) or (max-length: 80) The length
range Number out of range The bound broken: (minimum: 1), (exclusive-minimum: 1), (maximum: 10) or (exclusive-maximum: 10) The number
multiple Not a multiple of multiple-of (multiple-of: 0.1) The number
integer A fractional number where an integer is expected The number
items Too few or too many array items The bound broken: (min-items: 1) or (max-items: 5) The item count
unique Duplicate array items The two duplicate indices
union Several alternatives take the value’s type but none matches, or more than one one-of member matches The alternatives’ kinds
not The value matches a not-of schema

format-errors(errors) turns the records into parse’s report, reading only path and message:

#import "@preview/gairm-import:0.13.0": (
  validate, coerce, format-errors, schema-from-json-schema,
)

#let resume-schema = schema-from-json-schema(json("resume.schema.json"))
#let doc = json("resume.json")
#let errors = validate(doc, schema: resume-schema)
#if errors.len() > 0 {
  [Resume has #errors.len() issue(s).]
  raw(format-errors(errors))
} else {
  let model = coerce(doc, schema: resume-schema)
  // render model …
}

Null handling

By default JSON null means “absent”, as most JSON Resume emitters intend ("summary": null is the same as no summary). Pass strict-null: true to parse, validate or coerce when null must mean something: it is then an ordinary value that a schema accepts or rejects.

Input Default strict-null: true
required key missing required required
key holding null, field not nullable required if required, else dropped from the model type, “got null”
key holding null, field nullable(X) dropped accepted, kept as none
unknown key holding null unknown-key unknown-key
null array element dropped type, or kept if the element is nullable(X) (and counted by min-items / unique-items)
dependent-required trigger holding null does not fire fires
object whose keys are all null kept as (:) judged key by key
free-form object (no fields, additional: true) passed through as given, nulls and all the same
the whole document is null panics panics

nullable(X) accepts null or whatever X accepts, and judges a non-null value exactly as X does:

#import "@preview/gairm-import:0.13.0": parse, object, string, nullable

#let schema = object(
  (name: string(), nickname: nullable(string())),
  required-keys: ("name", "nickname"),
)
#parse((name: "Ada", nickname: none), schema: schema, strict-null: true)
// → (name: "Ada", nickname: none)

The JSON Resume schema declares no nullable fields, so with strict-null: true it rejects a null in any declared field. The free-form custom objects check nothing, so a null there is kept.

Validating a JSON Resume

JSON Resume publishes its schema as a JSON Schema document. Save a copy beside your file, from jsonresume.org/schema or the @jsonresume/schema npm package, and translate it:

#import "@preview/gairm-import:0.13.0": parse, schema-from-json-schema

#let resume-schema = schema-from-json-schema(json("resume.schema.json"))
#let resume = parse(path("resume.json"), schema: resume-schema)
// hand `resume` to any compatible Typst CV template

A minimal resume.json:

{
  "basics": {
    "name": "Seán Ó Murchú",
    "label": "Senior Software Engineer",
    "email": "sean@example.com",
    "summary": "Backend engineer with eight years of experience."
  },
  "work": [
    {
      "name": "Acme Corp",
      "position": "Senior Software Engineer",
      "startDate": "2022-01",
      "highlights": ["Led the event-sourcing platform migration."]
    }
  ]
}

The result mirrors the document: resume.basics.name and resume.work.at(0).position are strings, resume.work.at(0).highlights an array of strings. Your copy of the schema decides the version, so a field upstream adds works as soon as you update the file. Pass the result to any renderer that takes JSON Resume data, such as altacv:

#import "@preview/altacv:1.7.0": alta
#import "@preview/gairm-import:0.13.0": parse, schema-from-json-schema

#let resume-schema = schema-from-json-schema(json("resume.schema.json"))
#alta(parse(path("resume.json"), schema: resume-schema))

Upstream sets additionalProperties: true at the top level and on every section’s items, so undeclared keys pass. Its date fields (startDate, endDate, date, …) are strings checked by its iso8601 regex, and meta.lastModified is a plain string. For a stricter schema, edit the document before translating it and the schema after:

  • close every object that declares properties, so an undeclared key is an error. Typed extras (additionalProperties with a schema) still pass if they match, and the free-form custom objects, which declare none, stay open;
  • check the date fields as format: "date", which also takes a Typst datetime, and meta.lastModified as a date-time or a date;
  • make the free-text fields Typst content, so they splice into markup.
#import "@preview/gairm-import:0.13.0": (
  parse, schema-from-json-schema, lens-put, content-type,
)

// Not for schemas with `not` or `if`: closing an object there loosens them.
#let close(js) = if type(js) == dictionary {
  let js = js.pairs().map(((k, v)) => (k, close(v))).to-dict()
  if (
    "properties" in js and js.at("additionalProperties", default: true) == true
  ) {
    js.additionalProperties = false
  }
  js
} else if type(js) == array { js.map(close) } else { js }

#let strict-json = {
  let js = close(json("resume.schema.json"))
  js.definitions.iso8601 = (type: "string", format: "date")
  js.properties.meta.properties.lastModified = (
    anyOf: (
      (type: "string", format: "date-time"),
      (type: "string", format: "date"),
    ),
  )
  js
}

#let resume-schema-strict = (
  ("objective",),
  ("basics", "summary"),
  ("work", "items", "summary"),
  ("work", "items", "highlights", "items"),
  ("volunteer", "items", "summary"),
  ("volunteer", "items", "highlights", "items"),
  ("education", "items", "summary"),
  ("awards", "items", "summary"),
  ("certificates", "items", "summary"),
  ("publications", "items", "summary"),
  ("references", "items", "reference"),
  ("projects", "items", "summary"),
  ("projects", "items", "description"),
  ("projects", "items", "highlights", "items"),
).fold(
  schema-from-json-schema(strict-json),
  (schema, at) => lens-put(schema, at, content-type),
)

#let resume = parse(path("resume.json"), schema: resume-schema-strict)

For a different mix, or for a renderer’s own fields, edit either schema with lenses; see REFERENCE.md.

The deprecated exports resume-schema and resume-schema-strict are these two schemas, built from a bundled copy of JSON Resume 1.7.0.

Reference

REFERENCE.md documents every constructor and argument, the formats, lenses and the edits, introspection, JSON Pointer, the JSON Schema translator and its deviations from draft 7, and the deprecated names.

Contributing

See CONTRIBUTING.md. Releases are cut by release-please from conventional-commit titles on main.

License

MIT.