Skip to main content

kson-lang

Python bindings for KSON, a next-gen configuration language. Convert KSON to JSON/YAML, format and validate documents, and parse KSON into structured values.

Requires Python 3.11+. Prebuilt wheels are published for Linux x86_64 (glibc 2.34+), macOS arm64 and Windows x86_64.

Installation

pip install kson-lang

Installing needs one of those wheels: kson-lang wraps a native library and the source distribution cannot build one, so anywhere else pip falls back to the sdist and fails with a pointer to Build from source.

Quick start

from kson import Kson, TranspileOptions, Result

result = Kson.to_json("key: [1, 2, 3, 4]", TranspileOptions.Json(retain_embed_tags=False))
assert isinstance(result, Result.Success)
print(result.output())
{
  "key": [
    1,
    2,
    3,
    4
  ]
}

Converting to JSON

Use Kson.to_json() to transpile KSON source into JSON. The result is either Result.Success or Result.Failure:

from kson import Kson, TranspileOptions, Result

result = Kson.to_json(
    "name: Alice\nage: 30",
    TranspileOptions.Json(retain_embed_tags=False),
)

if isinstance(result, Result.Success):
    print(result.output())
elif isinstance(result, Result.Failure):
    for error in result.errors():
        print(f"Error: {error.message()}")

Set retain_embed_tags=True to preserve embed block metadata in the JSON output (see Embed blocks).

Converting to YAML

Use Kson.to_yaml() to transpile KSON to YAML. Comments are preserved:

from kson import Kson, TranspileOptions, Result

result = Kson.to_yaml(
    "# my config\nname: Alice\nage: 30",
    TranspileOptions.Yaml(retain_embed_tags=False),
)

if isinstance(result, Result.Success):
    print(result.output())

Formatting

Use Kson.format() to reformat KSON source. Choose a formatting style and indentation:

from kson import Kson, FormatOptions, IndentType, FormattingStyle

options = FormatOptions(
    indent_type=IndentType.Spaces(2),
    formatting_style=FormattingStyle.PLAIN,
    embed_block_rules=[],
)

formatted = Kson.format("key: [1, 2, 3, 4]", options)
print(formatted)
key:
  - 1
  - 2
  - 3
  - 4

Formatting styles

Style Description
FormattingStyle.PLAIN YAML-like format (default)
FormattingStyle.CLASSIC Standard JSON format with braces and quotes
FormattingStyle.DELIMITED JSON-like with explicit delimiters
FormattingStyle.COMPACT Minified single-line output

Indentation

  • IndentType.Spaces(n) — indent with n spaces
  • IndentType.Tabs() — indent with tabs

Parsing and analysis

Use Kson.analyze() to parse KSON into tokens and a structured value tree:

from kson import Kson, KsonValue

analysis = Kson.analyze("name: Alice\nscores: [95, 87, 92]", None, None)

# Check for parse errors
for error in analysis.errors():
    print(f"{error.severity().name}: {error.message()}")

# Access the parsed value tree
value = analysis.kson_value()
if isinstance(value, KsonValue.KsonObject):
    props = value.properties()

    name = props["name"]
    if isinstance(name, KsonValue.KsonString):
        print(f"Name: {name.value()}")  # "Alice"

    scores = props["scores"]
    if isinstance(scores, KsonValue.KsonArray):
        for element in scores.elements():
            if isinstance(element, KsonValue.KsonNumber.Integer):
                print(f"Score: {element.value()}")

Value types

All parsed values are subclasses of KsonValue:

Type Access
KsonValue.KsonObject .properties() returns dict[str, KsonValue]
KsonValue.KsonArray .elements() returns list[KsonValue]
KsonValue.KsonString .value() returns str
KsonValue.KsonNumber.Integer .value() returns int
KsonValue.KsonNumber.Decimal .value() returns float
KsonValue.KsonBoolean .value() returns bool
KsonValue.KsonNull (no value)
KsonValue.KsonEmbed .tag() returns str or None, .content() returns str

Every value also has .start() and .end() returning a Position with .line() and .column() (both 0-based), useful for editor tooling and diagnostics.

Token access

from kson import Kson

analysis = Kson.analyze("key: value", None, None)
for token in analysis.tokens():
    print(f"{token.token_type().name}: {repr(token.text())}")

Schema validation

Parse a JSON Schema definition and validate KSON documents against it:

from kson import Kson, SchemaResult

schema_result = Kson.parse_schema("""
type: object
properties:
  name:
    type: string
  age:
    type: integer
required: [name, age]
""")

if isinstance(schema_result, SchemaResult.Success):
    validator = schema_result.schema_validator()

    errors = validator.validate("name: Alice\nage: 30", None)
    assert errors == []  # Valid

    errors = validator.validate("name: Alice\nage: not-a-number", None)
    for error in errors:
        print(f"Validation error: {error.message()}")

Embed blocks

KSON supports embed blocks for embedding raw content like SQL, HTML, or other languages. When parsing:

from kson import Kson, KsonValue

analysis = Kson.analyze("query: $sql\nSELECT * FROM users\n$$", None, None)
value = analysis.kson_value()

if isinstance(value, KsonValue.KsonObject):
    embed = value.properties()["query"]
    if isinstance(embed, KsonValue.KsonEmbed):
        print(f"Tag: {embed.tag()}")        # "sql"
        print(f"Content: {embed.content()}")  # "SELECT * FROM users"

When converting to JSON/YAML, use retain_embed_tags=True to keep embed metadata or False to flatten embed blocks to plain strings.

Embed rules for formatting

Use embed rules to tell the formatter which string values should be rendered as embed blocks:

from kson import Kson, FormatOptions, IndentType, FormattingStyle, EmbedRule, EmbedRuleResult

source = 'scripts:\n  deploy: "#!/bin/bash\\necho hello"'

rule_result = EmbedRule.from_path_pattern("/scripts/*", "bash", 0)
assert isinstance(rule_result, EmbedRuleResult.Success)

options = FormatOptions(
    indent_type=IndentType.Spaces(2),
    formatting_style=FormattingStyle.PLAIN,
    embed_block_rules=[rule_result.embed_rule()],
)

formatted = Kson.format(source, options)

Error handling

All conversion methods (to_json, to_yaml) return a Result:

from kson import Kson, TranspileOptions, Result

source = "name: Alice\nage: 30"
result = Kson.to_json(source, TranspileOptions.Json(retain_embed_tags=False))

match result:
    case Result.Success():
        print(result.output())
    case Result.Failure():
        for error in result.errors():
            pos = error.start()
            print(f"  Line {pos.line()}, col {pos.column()}: {error.message()}")

Kson.parse_schema() returns a SchemaResult with the same pattern (SchemaResult.Success / SchemaResult.Failure).

Build from source

git clone https://github.com/kson-org/kson.git
cd kson && ./gradlew :lib-python:assemble
pip install ./lib-python

Metadata

Release files for kson-lang 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for kson-lang 0.4.0
File Size Uploaded Provenance Actions
kson_lang-0.4.0.tar.gz 24.3 kB Without provenance Details for kson_lang-0.4.0.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for kson-lang 0.4.0
File Interpreter ABI Platform Actions
kson_lang-0.4.0-cp310-abi3-win_amd64.whl CPython 3.10 abi3 Windows x86-64 Details for kson_lang-0.4.0-cp310-abi3-win_amd64.whl
kson_lang-0.4.0-cp310-abi3-manylinux_2_34_x86_64.whl CPython 3.10 abi3 Linux glibc 2.34+ x86-64 Details for kson_lang-0.4.0-cp310-abi3-manylinux_2_34_x86_64.whl
kson_lang-0.4.0-cp310-abi3-macosx_11_0_arm64.whl CPython 3.10 abi3 macOS 11.0+ ARM64 Details for kson_lang-0.4.0-cp310-abi3-macosx_11_0_arm64.whl

Total release size: 18.1 MB

Release files / kson_lang-0.4.0.tar.gz

Download URL kson_lang-0.4.0.tar.gz
Size 24.3 kB
Tags Source
SHA-256 checksum
How to use checksums
880585bd690109a81f7e6e6c16f6dd7a13615b0a3199ce3867ced1b72c5fcb5d
BLAKE2b-256 checksum
How to use checksums
27c9cf2adfc0ff933aa5ae498598989099f9e830351f9e88aaf684d0ca2923e1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / kson_lang-0.4.0-cp310-abi3-win_amd64.whl

Download URL kson_lang-0.4.0-cp310-abi3-win_amd64.whl
Size 6.0 MB
Tags CPython 3.10 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
c82e351977d94cb9a1a873429c7c5c57cc54374262434500d27b6d1377a6e36a
BLAKE2b-256 checksum
How to use checksums
210e2c6433d848d7ec305bf6ea7254e84d1de7a11e1bb4f34397475e052c9153
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / kson_lang-0.4.0-cp310-abi3-manylinux_2_34_x86_64.whl

Download URL kson_lang-0.4.0-cp310-abi3-manylinux_2_34_x86_64.whl
Size 6.2 MB
Tags CPython 3.10 Linux glibc 2.34+ x86-64 abi3
SHA-256 checksum
How to use checksums
5b81f00f1e36431d7726c925c01770f963add8c5cbfa55e9c126d30afcfab17e
BLAKE2b-256 checksum
How to use checksums
83d83f8cd3eaa7bfe4b4460996a10cf21788649b889093ab1259bb73f3f3332d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / kson_lang-0.4.0-cp310-abi3-macosx_11_0_arm64.whl

Download URL kson_lang-0.4.0-cp310-abi3-macosx_11_0_arm64.whl
Size 5.9 MB
Tags CPython 3.10 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
0e767cf5032935f84753e3a60bc5614bce57acb633dafb243566fc72ba2fc2f6
BLAKE2b-256 checksum
How to use checksums
d9319e36b73ad09c200be23d243eb08d0573043fed0784cb02a4443026f8dcb8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Security for kson-lang 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page