Skip to content

Parse incomplete JSON (like what ChatGPT generates in stream mode) in Kotlin, obtain as much as possible information fastly.

License

Notifications You must be signed in to change notification settings

FunnySaltyFish/partial-json-parser-kmp

Repository files navigation

Partial-JSON-Paser-KMP

Kotlin Version Maven Central License

badge-android badge-ios badge-js badge-jvm badge-linux

中文

Introduction

This library helps to parse partial JSON (that is, incomplete JSON) in Kotlin. It is implemented in pure Kotlin so that can be used in KMP project.

Usage

import com.funnysaltyfish.partialjsonparser.PartialJsonParser

val partialJson = "{\"key\":\"Hello, "
val map = PartialJsonParser.parse(partialJson) as? Map<*, *> // Map(key=Hello, )
println(map) // {key=Hello, }
println(map?.get("key")) // Hello,

The method will throw JsonParseException if the JSON is invalid. In some extreme cases, it might also throw IndexOutOfBoundsException.

Actually, parse is just a combination of tokenize and parseTokens, you can use them separately if you want

fun parse(str: String): Any? {
    val tokens = Tokenizer.tokenize(str)
    return Parser.parseTokens(tokens)
}

Implementation

The library is published to Maven Central.

implementation("io.github.funnysaltyfish:partial-json-parser:1.0.2")

Examples

Below are some examples: (originJsonString -> parsed map)

{"ke                      -> {}
{"key"                    -> {}
{"key":                   -> {}
{"key":"te                -> {key=te}
{"key":"text", "key2      -> {key=text}
{"key":"text", "key2":"t} -> {key=text, key2=t}}

{"k":[1,2,3               -> {k=[1.0, 2.0, 3.0]}
{"k":[[1,2                -> {k=[[1.0, 2.0]]}
{"k":[[1,2],["v"          -> {k=[[1.0, 2.0], [v]]}
{"k":{"k2":1              -> {k={k2=1.0}}
{"k":{"k2":1, "k3":2      -> {k={k2=1.0, k3=2.0}}
{"k":{"k2":1, "k3":       -> {k={k2=1.0}}
{"k":[{"k2":1, "k3":2     -> {k=[{k2=1.0, k3=2.0}]}

To see more examples, please run ParseTest.kt.

Origin Source

Interestingly, the code is converted from the TypeScript library here by GitHub Copilot, I make it suitable for Kotlin style, modify some extreme cases, write some tests and publish it to Maven Central. Thanks for it.

About

Parse incomplete JSON (like what ChatGPT generates in stream mode) in Kotlin, obtain as much as possible information fastly.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages