[Bug] juce::JSON::parse ignoring end of JSON

Hello,

I’m attempting to parse an improperly formatted JSON string using JUCE:

juce::var json;

juce::String jsonString =  "{\n   \"value\": false\n}sssss"

juce::Result res = juce::JSON::parse(jsonString, json);

However, the juce::JSON::parse function is returning without any issues.

I think what happens here is that the parser tries to parse an object or an array so it looks for either a { or [ for the opening character and keeps parsing until it finds the corresponding closing ‘}’ or ‘]’. Effectively this means it ignores the remaining characters. Is this a problem for you?

You could maybe detect this with something like (untested)…

bool jsonContainsTrailingCharacters (const juce::String& jsonString)
{
    const trimmedJsonString = jsonString.trimEnd();
    return ! (trimmedJsonString.endsWithChar ('}') || trimmedJsonString.endsWithChar (']'))
}

Or if you need to clean it up you could do something like (again untested)…

jsonSting = jsonSting.subString (0, jsonString.lastIndexOfAnyOf ("}]") + 1);

Thank you for your insights! The issue is not a blocking problem.

However, in the context of handling JSON data in an HTTP environment, allowing users to send badly formatted JSON could pose a potential concern. It might be worth considering additional validation or cleanup steps to ensure that the received JSON adheres to the expected format, as defined in the JSON specification (RFC 8259).

There are more parsing functions in juce that are that kind of lenient, and usually that is quite handy.

Another example is:

juce::String k ("12 kg");
auto value = k.getIntValue(); // returns 12

The JSON::parse allows that way to use the same code to parse nested objects. Although with that API that wouldn’t work anyway, because you don’t know what portion was parsed.

I would file that as legitimate feature request like rightly pointed out.

2 Likes