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 withnspacesIndentType.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)
# 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)
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)
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:build
pip install ./lib-python
Links
Metadata
Release files for kson-lang 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| kson_lang-0.3.0.tar.gz | 24.2 kB | Details |
Built distributions (wheels)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| kson_lang-0.3.0-cp310-abi3-win_amd64.whl | CPython 3.10 | abi3 | Windows x86-64 | Details |
| kson_lang-0.3.0-cp310-abi3-manylinux_2_34_x86_64.whl | CPython 3.10 | abi3 | Linux glibc 2.34+ x86-64 | Details |
| kson_lang-0.3.0-cp310-abi3-macosx_11_0_arm64.whl | CPython 3.10 | abi3 | macOS 11.0+ ARM64 | Details |
Total release size: 17.9 MB
Release files / kson_lang-0.3.0.tar.gz
| Download URL | kson_lang-0.3.0.tar.gz |
|---|---|
| Size | 24.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
38a740a851546c6aaf488d1f323b4150f80149e65fcef0d04c5a113562cfb30d
|
|
BLAKE2b-256 checksum How to use checksums |
605716ccf175f90216ee3103aaafb9b05bca45e340e0010c355c7dbd56fdbc0f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.13.13
|
Release files / kson_lang-0.3.0-cp310-abi3-win_amd64.whl
| Download URL | kson_lang-0.3.0-cp310-abi3-win_amd64.whl |
|---|---|
| Size | 5.9 MB |
| Tags | CPython 3.10 Windows x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
bb830075301b3450b191d7de88009f5d38b528627d470b5ed20b3ea8f6da06a2
|
|
BLAKE2b-256 checksum How to use checksums |
1d644f0867bec89e94c81de6f1654ab812fd755a31c29bc49462ba513d4f2eb3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.13.13
|
Release files / kson_lang-0.3.0-cp310-abi3-manylinux_2_34_x86_64.whl
| Download URL | kson_lang-0.3.0-cp310-abi3-manylinux_2_34_x86_64.whl |
|---|---|
| Size | 6.1 MB |
| Tags | CPython 3.10 Linux glibc 2.34+ x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
45c7b9bb69df90ab9f8b7e5667adc2a8ca2bc78717f69a84d60176534c37419f
|
|
BLAKE2b-256 checksum How to use checksums |
53d5d7422c46b4cbccb67117b61677ca71532ee417481ca77e24426467457a25
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.13.13
|
Release files / kson_lang-0.3.0-cp310-abi3-macosx_11_0_arm64.whl
| Download URL | kson_lang-0.3.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 |
eeb071eb8c9c77e7d5d361ee1b441e44acae98d9db126a12cf7c4c4ab70e0fa4
|
|
BLAKE2b-256 checksum How to use checksums |
cd3df4c6092c4d18c9dd0a0c0bce99bdc5d40224238e5e5221d569ee16e4525b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.13.13
|