literalizer

literalizer converts JSON, JSONC, JSON5, YAML, and TOML data structures to native language literal syntax.

Supported languages

See Languages for the full list with per-language options.

Installation

Requires Python 3.12+.

pip install literalizer

Usage

Use literalizer.literalize() to convert data to native language literals. Pass your data, its format, and a target language:

"""Minimal example of using literalizer."""

from literalizer import InputFormat, literalize
from literalizer.languages import Python

result = literalize(  # returns LiteralizeResult with .code and .preamble
    source='{"x": 1}',
    input_format=InputFormat.JSON,
    language=Python(),
)
# result.code:
# {
#     "x": 1,
# }

The call returns a single LiteralizeResult. Here result.code is the whole story, but for some languages and options the literal in code relies on a separate preamble to compile. See Understanding the result for what each field means and how to assemble output that compiles.

Configure the language to control how individual data types are rendered. Comments in the source are preserved using the target language’s comment syntax:

"""Layering format options on top of the minimal call."""

from literalizer import InputFormat, literalize
from literalizer.languages import Go

yaml_config = """\
# Server configuration
host: localhost  # default host
port: 8080
released: 2026-06-02
"""
result = literalize(
    source=yaml_config,
    input_format=InputFormat.YAML,
    language=Go(date_format=Go.date_formats.ISO),
)
# result.code:
# map[string]any{
#     // Server configuration
#     "host": "localhost",  // default host
#     "port": 8080,
#     "released": "2026-06-02",
# }

TOML is read the same way, and its comments are preserved too:

"""Reading TOML, with comments preserved."""

from literalizer import InputFormat, literalize
from literalizer.languages import Python

toml_config = """\
# Server configuration
host = "localhost"  # default host
port = 8080
"""
result = literalize(
    source=toml_config,
    input_format=InputFormat.TOML,
    language=Python(),
)
# result.code:
# {
#     # Server configuration
#     "host": "localhost",  # default host
#     "port": 8080,
# }

JSONC and JSON5 are also accepted. The relaxed JSON5 syntax, such as comments, single-quoted strings, trailing commas, and hexadecimal numbers, is converted to the target language:

"""Reading JSON5's relaxed syntax."""

from literalizer import InputFormat, literalize
from literalizer.languages import Python

json5_config = """\
{
  // Relaxed syntax is accepted here.
  name: 'literalizer',
  port: 0x1F90,
}"""
result = literalize(
    source=json5_config,
    input_format=InputFormat.JSON5,
    language=Python(),
)
# result.code:
# {
#     # Relaxed syntax is accepted here.
#     "name": "literalizer",
#     "port": 8080,
# }

JSONC and JSON5 comment attachment

Line comments (//) and block comments (/* ... */) follow the same formatting, neutralization, and language capability rules as YAML and TOML comments. Source comment delimiters and surrounding whitespace are removed; each line of a block comment is preserved as comment text.

  • Document headings attach before the first collection entry. Comments in an empty root collection move before its declaration. Comments in a nested empty collection move before its parent entry, preserving the target’s typed empty-collection syntax.

  • Standalone comments before an entry attach to that entry. Comments between a mapping key, its colon, and its value also attach before that entry.

  • Comments starting on the same line as a completed value attach inline to that entry, including comments after its comma. Consecutive same-line comments are joined with a space. Further lines of a multiline block attach before the next entry, or trail the collection when there is no next entry.

  • Comments before a closing delimiter trail that collection. Comments after the root collection trail its entries. Nested collections keep their own comment associations.

  • Scalar documents retain headings, inline comments, and following standalone comments. Targets that cannot place a comment there move it before the declaration, following their existing scalar comment policy.

  • Targets that cannot place comments inside collections move them before the declaration. For per-element calls, comments inside an argument row move before that row’s call; row comments remain before or inline with the call. Whole-document calls move input comments before the call. The existing wrapped-call capability checks also apply to these comments.

JSONC retains strict JSON syntax, including rejecting trailing commas. JSON5 retains its relaxed syntax. Comment-like text inside strings is data.

Binding the result to a variable

By default literalize() renders a bare literal. Pass variable_form to bind that literal to a variable instead, so the output is a statement you can drop straight into source. There are three forms, and the difference is visible in languages that distinguish declaring a variable from assigning to one:

  • NewVariable declares a fresh variable (Go’s config :=, JavaScript’s const config =, Rust’s let config =). This is the form nearly every example uses.

  • ExistingVariable assigns to a variable declared elsewhere (config =), emitting no declaration keyword.

  • BothVariableForms emits a declaration and a subsequent assignment together, for showing both styles from one source. It requires wrap_in_file=True and a language whose declaration style permits reassigning the same name.

The same source, rendered for Go in each form:

"""Contrast the three variable_form choices for one source."""

from literalizer import (
    BothVariableForms,
    ExistingVariable,
    InputFormat,
    NewVariable,
    literalize,
)
from literalizer.languages import Go

source = '{"host": "localhost", "port": 8080}'

new_variable = literalize(
    source=source,
    input_format=InputFormat.JSON,
    language=Go(),
    variable_form=NewVariable(name="config", modifiers=frozenset()),
)
assert new_variable.code == (
    'config := map[string]any{\n\t"host": "localhost",\n\t"port": 8080,\n}'
)

existing_variable = literalize(
    source=source,
    input_format=InputFormat.JSON,
    language=Go(),
    variable_form=ExistingVariable(name="config"),
)
assert existing_variable.code == (
    'config = map[string]any{\n\t"host": "localhost",\n\t"port": 8080,\n}'
)

both_forms = literalize(
    source=source,
    input_format=InputFormat.JSON,
    language=Go(),
    variable_form=BothVariableForms(
        name="config",
        modifiers=frozenset(),
    ),
    wrap_in_file=True,
)
assert both_forms.code == (
    "package main\n"
    "\n"
    "func main() {\n"
    "config := map[string]any{\n"
    '\t"host": "localhost",\n'
    '\t"port": 8080,\n'
    "}\n"
    "config = map[string]any{\n"
    '\t"host": "localhost",\n'
    '\t"port": 8080,\n'
    "}\n"
    "_ = config\n"
    "}"
)

Whether the two forms differ at all depends on the language. Python uses config = for both declaring and assigning, so with the default settings NewVariable and ExistingVariable render identically. They diverge once a feature attaches to the declaration specifically: enabling variable_type_hints makes NewVariable annotate the binding (config: dict[str, str | int] = ...) while ExistingVariable stays a bare config = ....

Use cases

  • Generate test fixtures from JSON, JSONC, JSON5, YAML, or TOML samples.

  • Convert API responses to language-native data structures for documentation.

  • Generate multi-language function call examples from data (see Rendering function calls).

  • Create type-safe literal data from JSON, JSONC, JSON5, YAML, or TOML config files.

CLI

A command-line interface is available at literalizer-cli.

Sphinx extension

A Sphinx extension is available at sphinx-literalizer.

Reference

Reference

Project / Development