Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
laskovenko1 opened this issue Nov 21, 2023 · 3 comments

Comments

@laskovenko1
Copy link

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
@joffrey-bion
Copy link

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.

@markuskreusch
Copy link

Had this problem today and it took me a while to figure out what actually went wrong in the code because this is totally unexpected. Invalid JSON input should cause an exception while parsing and not just parse as a JsonPrimitive with unclear semantics (isString = false but not a boolean / number / null either does not make any sense).

This needs to be fixed because there is no clear way to check if a value is valid JSON or not. Current workaround: Parse the string and check if isString is false and content equals the input value afterwards. This only works because I do not accept numbers, nulls or booleans at this place.

@sandwwraith
Copy link
Member

Related: #1298

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants