File handling JSON Serialization

JSON File Handling

The klyn.io.json package serializes Klyn objects, maps, lists, strings, numbers, booleans, and null values to JSON, and parses JSON back into typed Klyn values.

Imports

import klyn.collections
import klyn.io
import klyn.io.json

Stringify Values

JSON.stringify returns compact JSON by default and can also write directly to a file path or writer.

import klyn.io.json

config = {"fullscreen": true, "theme": "dark"}

compact = JSON.stringify(config, spaces=false)
pretty = JSON.stringify(config, pretty=true, indent=2)

print(compact)
print(pretty)

Write and Read Files

Use the overload that accepts a filename for short writes, or combine FileWriter and FileReader when you need explicit resource management.

import klyn.collections
import klyn.io
import klyn.io.json

filename = "config.json"
config = {"fullscreen": true, "theme": "dark"}

JSON.stringify(filename, config)

data = JSON.parseMap(FilePath(filename))
fullscreen = data["fullscreen"] as Boolean
theme = data["theme"] as String

print(fullscreen)
print(theme)

Typed Parse

JSON.parse<TYPE>(...) asks the parser to materialize the expected type. This keeps the static type visible at the call site.

import klyn.collections
import klyn.io.json

data = JSON.parse<SortedMap<String, Object>>("""{"theme":"dark","retries":3}""")
assert data["theme"] as String == "dark"
assert data["retries"] as Int == 3

Without a requested type, integer tokens become Int when they fit its signed 32-bit range, or Long otherwise. Decimal and exponent tokens become Double. Numbers outside these supported ranges raise JSONParseException, rather than being silently truncated. Escaped \u0000 is preserved in strings and object keys, including when the document is serialized again.

Validate external JSON

JSON preserves structure, not business rules. Treat parsed maps as untrusted input until required keys, value types, ranges, and enum-like strings have been checked.