FR: change JSON::toString output to match php & javascript json_encode

Php’s json_encode produces json-formatted text that does not have a space after the ":".

JUCE’s JSON::toString does.

It happens here in void DynamicObject::writeAsJSON (OutputStream& out, const int indentLevel, const bool allOnOneLine, int maximumDecimalPlaces):

        out << '"';
        JSONFormatter::writeString (out, properties.getName (i));
        out << "\": ";

Javascript’s stringify() function, which converts javascript objects to json, also does not add this space after the :

I’m requesting this because I hash the JSON output from JUCE’s JSON::toString functions to produce SHA signatures.
On my server, I try to recreate those signatures to verify the data, and if the original JUCE-created JSON has characters that the server’s JSON encoders don’t include, the signatures will never match.

1 Like

To be safe i would compare the data after stripping all whitespace on both sides.

2 Likes

+1 to rebbur’s suggestion

A standard library that exists in different languages is json minify. It removes all layout characters, like space, newlines, tabs…
I don’t think it makes sense to change the output for one specific use case.

IME it’s rarely a good idea to rely on a particular format for utilities like this that are largely intended for human-readability. If you need to convert a JSON object to a string in a specific format, you should probably write that conversion yourself, or at least do some additional sanitation on the output from another API like JUCE’s.

For your usecase, would it not be enough to do

const auto sanitisedJSON = unsanitisedJSON.replace (": ", ":")`

This would break, if inside a quoted text the phrase ": " would be found.
You need to preserve the values…

True. Depends how much OP knows about the data stored in the objects as to whether or not that would be safe.

thanks @daniel @ImJimmi @rebbur

I am creating the json on both the server side and the client side.

I think I need to look into how I am sanitizing on both sides and figure out the best way to create JSON on the JUCE side that doesn’t end up looking like this:

"{\"versionString\":\"1.0.0\",\"data\":\"ew0KICAidGVzdCI6ICJ2YWx1ZSINCn0=\",\"clientPublicKey\":\"-----BEGIN PUBLIC KEY-----\\nMCowDQYJKoZIhvcNAQEBBQADGQAwFgIRAJ6k+IvCAPEA6JmOdyfa4qECAQU=\\n-----END PUBLIC KEY-----\\n\",\"testKey1\":\"testValue1\",\"testKey2\":\"testValue2\"}"

where a bunch of characters (quotes, slashes) are being escaped.

I tend to embed JSON strings like so:

const juce::String jsonData = R"(
    {
        "foo": "bar"
    }
)";

I’m constructing them from juce::var objects, they aren’t hard-coded.