json-stream
0.0.2indexedStreaming JSON parser emitting flat token events for incremental, chunked input; supports suspending reads, building or skipping value trees, and efficient selective field extraction.
Streaming JSON parser emitting flat token events for incremental, chunked input; supports suspending reads, building or skipping value trees, and efficient selective field extraction.
A streaming JSON parser for Kotlin Multiplatform (JVM, JS, WasmJS).
Emits a flat stream of events (StartObject, EndObject, StartArray,
EndArray, Value) as it tokenizes JSON input, without building an in-memory
tree. Designed for incremental / push-based parsing where input arrives in
chunks.
JsonParser is the low-level, non-suspending parser. You push byte chunks
into it and pull events out:
val p = JsonParser()
p.push("""{"key": "value", "n": 42}""".encodeToByteArray())
p.finish()
while (true) {
val event = p.next() ?: break
when (event) {
JsonEvent.StartObject -> println()
JsonEvent.EndObject -> println()
JsonEvent.StartArray -> println()
JsonEvent.EndArray -> println()
JsonEvent.Value -> println()
JsonEvent.InProgress -> { }
}
}
Input can be fed incrementally. When the parser needs more data it returns
JsonEvent.InProgress. Push another chunk and continue calling next():
val p = JsonParser()
p.push(firstChunk)
while (true) {
val event = p.next()!!
if (event is JsonEvent.InProgress) break
// handle event
}
p.push(secondChunk)
p.finish()
while (true) {
val event = p.next() ?: break
// handle event
}
next() returns null only when the whole document has been parsed
successfully, and JsonEvent.InProgress when the current chunk has been
consumed and more input is required -- push the next chunk and call next()
again.
finish() marks the end of the input and may be called more than once;
repeated calls are a no-op. Calling next() after finish() while the parser
still waits for input raises JsonParseException with the end-of-input
offset, so null always means the document was complete.
Malformed input raises JsonParseException; its offset is the index of the
first byte that could not be accepted.
The parser is strict: numbers, true/false/null and string escapes must
follow RFC 8259, and raw control characters inside a string are rejected. A
leading UTF-8 BOM is skipped; UTF-16 input is not supported.
SuspendingJsonParser wraps JsonParser and reads from a Ktor
ByteReadChannel. It automatically feeds the underlying parser when it needs
more data, and never reports JsonEvent.InProgress. The channel stays owned
by the caller: the parser does not close or cancel it, not even on errors.
val parser = SuspendingJsonParser(byteReadChannel)
while (true) {
val event = parser.next() ?: break
when (event) {
is JsonEvent.Value -> println(parser.currentValue())
// ...
else -> {}
}
}
Convenience methods build kotlinx.serialization.json.JsonElement trees from
the event stream:
val element: JsonElement? = parser.nextJsonElement()
To skip over a value without allocating a JsonElement tree:
parser.skipJsonElement()
currentJsonElement() decodes the token reported by the last next() call and
throws IllegalStateException when there is none, so JsonNull from it always
means the JSON literal null. returns when the next
event is not a value, returns the next event and fails if it has
another type, and skips the value at the current position.
Combine next() with skipJsonElement() to efficiently extract specific
fields from large JSON without materializing the entire structure:
val parser = SuspendingJsonParser(channel)
parser.expect<JsonEvent.StartObject>()
while (true) {
when (val ev = parser.next()) {
is JsonEvent.Value -> {
fieldName = parser.currentValue()
(fieldName == ) {
value = parser.nextJsonElement()
} {
parser.skipJsonElement()
}
}
JsonEvent.EndObject ->
-> error()
}
}
Field names and values both emit Value, and nothing in the stream marks
which is which; a value always follows its field name, so track the container
state. Call currentValue() to get the raw JSON text of the token (strings
include their surrounding quotes and escape sequences). The token stays
readable until the next next() call, including across push() calls.
kotlinx-serialization-jsonkotlinx-coroutines-coreio.ktor:ktor-ioVersions are pinned in build.gradle.kts.
./gradlew build
Enable the versioned git hooks once per checkout:
./gradlew installGitHooks
The pre-commit hook refuses to commit while projectVersion in
gradle.properties matches an existing v<version> tag, so a version is not
reused after it has been released.
jvmTest runs the JSONTestSuite
conformance cases. The fetchJsonTestSuite task downloads them into
build/jsonTestSuite; a checkout in JSONTestSuite/ next to the build is used
instead when it exists.
The version lives in gradle.properties as projectVersion. After
./gradlew publishToMavenLocal, src/jvmTest/kotlin/publish.kt -v<version>
collects the artefacts into publish.zip; the -javadoc.jar it ships is an
empty stub, so no documentation generator is configured.
See LICENSE for details.
nextJsonElement()nullexpect<T>()skipJsonElement()| Event | Meaning |
|---|
StartObject | { |
EndObject | } |
StartArray | [ |
EndArray | ] |
Value | A complete value (string, number, boolean, null, or field name) |
InProgress | Buffer exhausted -- push more data (JsonParser only) |
Surfaced from shared tags and platforms — no rankings paid for.