cJSON icon indicating copy to clipboard operation
cJSON copied to clipboard

Messy object formatting (tab after colon instead of space)

Open MightyPork opened this issue 6 years ago • 2 comments

cJSON_Print() places \t after colon in objects.

This could work if all keys had the same length (shorter than tab size), but in practice it leads to messy formatting:

~/devel/cjson_test $ make run
cc main.c cJSON.c cJSON.h -lm -Wall -o main
./main
JSON:
{
        "name": "MyPayloadName",
        "descr":        "This is a payload.",
        "data": {
                "simple":       {
                        "descr":        "simple field",
                        "type": "u8",
                        "unit": "°C",
                        "value":        123
                }
        }
}

Changing line 1676 fixes it:

        if (output_pointer == NULL)
        {
            return false;
        }
        *output_pointer++ = ':';
        if (output_buffer->format)
        {
            *output_pointer++ = ' '; // <===
            //*output_pointer++ = '\t';
        }
        output_buffer->offset += length;

        /* print value */
        if (!print_value(current_item, output_buffer))
        {
            return false;
        }
~/devel/cjson_test $ make run
cc main.c cJSON.c cJSON.h -lm -Wall -o main
./main
JSON:
{
        "name": "MyPayloadName",
        "descr": "This is a payload.",
        "data": {
                "simple": {
                        "descr": "simple field",
                        "type": "u8",
                        "unit": "°C",
                        "value": 123
                }
        }
}

The indentation could also be configurable (I prefer two spaces), but that's a bigger change.

Since fixing this also means fixing the print unit tests, I didn't make a PR before the change is accepted.

MightyPork avatar Feb 02 '20 16:02 MightyPork

@MightyPork thanks your suggestion, one space is more in line with the convention I think, a PR is welcome :)

Alanscut avatar Feb 19 '20 07:02 Alanscut

Can you merge the PR #486 please ? I feel the use of tabulation instead of space is very unintuitive

TheRaf974 avatar Jan 01 '24 11:01 TheRaf974