simdjson-kotlin v0.1.0

Guides

DOM API

The DOM API parses an entire document into an immutable in-memory tree. Every node is a JsonValue you can navigate and re-read freely: random access, multiple passes, no ordering constraints.

Parsing

SimdJsonParser.parse accepts either a String or a UTF-8 ByteArray and returns the root JsonValue:

kotlin
val json: ByteArray = loadTwitterJson()

SimdJsonParser().use { parser ->
    val root = parser.parse(json) as JsonObject
    val statuses = root["statuses"] as JsonArray
    for (tweet in statuses) {
        val user = (tweet as JsonObject)["user"] as JsonObject
        if ((user["default_profile"] as JsonBoolean).value) {
            println((user["screen_name"] as JsonString).value)
        }
    }
}

The JsonValue tree

JsonValue is a sealed type with one subtype per JSON kind:

ParameterDescription
JsonObjectIterable<Pair<String, JsonValue>>Keyed map: get(key): JsonValue?, size, keys(): Set<String>, key in obj, and iteration over (key, value) pairs.
JsonArrayIterable<JsonValue>Ordered list: get(index): JsonValue, size, and iteration over elements.
JsonStringvalue classWraps value: String.
JsonNumberA number that remembers its representation (see Numbers).
JsonBooleanvalue classWraps value: Boolean.
JsonNullobjectThe null literal (a singleton).

Because the hierarchy is sealed, a when over it is exhaustive:

kotlin
val text: String? = when (val v = parser.parse(json)) {
    is JsonObject -> "object with ${v.size} entries"
    is JsonArray -> "array of ${v.size}"
    is JsonString -> v.value
    is JsonNumber -> v.toDouble().toString()
    is JsonBoolean -> v.value.toString()
    JsonNull -> null
}

get on a JsonObject returns JsonValue? (null when the key is absent). Indexing a JsonArray returns a non-null JsonValue. Casting to the wrong subtype throws a ClassCastException, so guard with as? or an is check when the shape is uncertain.

Numbers

JsonNumber preserves the parsed number’s representation so you can read it back without loss:

ParameterDescription
isIntegerBooleantrue for integers, signed or unsigned.
isLongBooleantrue for signed 64-bit integers.
isUnsignedBooleantrue for values that only fit in an unsigned 64-bit integer.
toLong() · toULong() · toInt()Integer views of the value.
toDouble()Floating-point view of the value.

Lifetime

The DOM tree is fully materialized and independent of the parser. It stays valid after later parse/iterate calls and even after the parser is closed. The parser itself still needs closing, since it owns reusable buffers and, on Native, native memory. use { } does that for you.

Errors

Parsing failures are subtypes of SimdJsonException:

ParameterDescription
JsonParsingExceptionSimdJsonExceptionInput is not valid JSON. Carries the byte offset of the failure.
JsonEncodingExceptionSimdJsonExceptionInput is not valid UTF-8.