ibireme / yyjson

The fastest JSON library in C
https://ibireme.github.io/yyjson/doc/doxygen/html/
MIT License
3.12k stars 267 forks source link

[BUG] Prettify JSON has wrong space when prettifying an array of number #178

Closed NghiaTranUIT closed 3 months ago

NghiaTranUIT commented 3 months ago

Describe the bug When prettifying a given JSON, the array of numbers lost their intent space.

Here is my code to prettify a given JSON String. Please note that YYJSON_READ_NUMBER_AS_RAW is important because we need to prettify the large floating number.

+(nullable NSString *) __useYYJSONToPrettifyWithText:(NSString *) text tabWidth:(NSInteger) tabWidth {
    // Convert to c-string
    auto cString = [text cStringUsingEncoding:NSUTF8StringEncoding];
    if (cString == nil) {
        return nil;
    }

    // Read JSON and get root
    yyjson_doc *idoc = yyjson_read(cString, strlen(cString), YYJSON_READ_NUMBER_AS_RAW); // important
    yyjson_mut_doc *doc = yyjson_doc_mut_copy(idoc, NULL);

    // To string, minified
    yyjson_write_flag flg = 0;
    if (tabWidth == 2) {
        flg = YYJSON_WRITE_PRETTY_TWO_SPACES;
    } else {
        flg = YYJSON_WRITE_PRETTY;
    }

    const char *jsonCString = yyjson_mut_write(doc, flg, NULL);
    if (jsonCString != NULL) {

        NSString *result = [NSString stringWithCString:jsonCString encoding:NSUTF8StringEncoding];

        // Free all
        free((void *)jsonCString);
        yyjson_doc_free(idoc);
        yyjson_mut_doc_free(doc);

        // Done
        return result;
    }

    // Free the doc
    yyjson_doc_free(idoc);
    yyjson_mut_doc_free(doc);

    return nil;
}

Input

{"name": "JSON Sample","ids": [1,2,3,4,5,6]}

Current output

{
  "name": "JSON Sample",
  "ids": [
1,
2,
3,
4,
5,
6
  ]
}

Expected output

{
  "name": "JSON Sample",
  "ids": [
    1,
    2,
    3,
    4,
    5,
    6
  ]
}

Your environment

ibireme commented 3 months ago

Fixed.

NghiaTranUIT commented 3 months ago

thanks so much, it's quick 🥇