kotlinx.serialization icon indicating copy to clipboard operation
kotlinx.serialization copied to clipboard

Parsing JSON with unquoted string literal to JsonElement is not prohibited in non-lenient mode

Open laskovenko1 opened this issue 2 years ago • 3 comments

Describe the bug

In accordance with the JSON specification, it is required that any string value be enclosed in quotes. However, when I attempt to parse inputs containing unquoted string values into a JsonElement, I observe that the resulting JSON tree contains malformed JsonLiteral objects (with content=str and isString=false).

Additionally, an intriguing observation prompted me to raise this issue: when I encode this JsonElement back to a string, the values are quoted, introducing what appears to be inconsistent behavior.

To Reproduce

    val jsonStr1 = """{"a": 1a}"""
    val jsonTree = Json { isLenient = false }.parseToJsonElement(jsonStr1)
    val jsonStr2 = Json { isLenient = false }.encodeToString(jsonTree)
    if (jsonStr1 != jsonStr2) throw IllegalStateException()

Expected behavior

SerializationException is thrown when malformed input parsed or jsonStr1 == jsonStr2

Environment

  • Kotlin version: 1.9.0
  • Library version: 1.6.1
  • Kotlin platforms: JVM

laskovenko1 avatar Nov 21 '23 14:11 laskovenko1

I just hit this today as well. If I pass a plain test or even /test string to parseToJsonElement, the parsing succeeds and I get a JsonLiteral, which then cannot be converted to any specific value. I believe parseToJsonElement should fail immediately instead.

joffrey-bion avatar Jan 28 '24 13:01 joffrey-bion