DaveGamble / cJSON

Ultralightweight JSON parser in ANSI C
MIT License
10.28k stars 3.15k forks source link

Always provide valuestring #831

Open mvoh opened 4 months ago

mvoh commented 4 months ago

Proposal

It would be very useful to always provide valuestring no matter what data type the value is. Example use cases:

It would extend the possibilities of cJSON while preserving C89 compatibility.

Code demonstration:

#include <stdio.h>
#include <stdlib.h>
#include <cjson/cJSON.h>

#define JSON_RAW "{\"number\":3000000000,\"ulonglong\":\"10000000000000000000\",\"hugeint\":\"1000000000000000000000000000000\"}"

int main()
{
    cJSON *overint32, *ulonglong;
    cJSON *json = cJSON_Parse(JSON_RAW);
    overint32 = cJSON_GetObjectItemCaseSensitive(json, "number");

    if (cJSON_IsNumber(overint32)) {
        printf("IsNumber. valueint=%d, valuedouble=%f, valuestring=\"%s\"\n", overint32->valueint, overint32->valuedouble, overint32->valuestring);
    }

    ulonglong = cJSON_GetObjectItemCaseSensitive(json, "ulonglong");

    if (cJSON_IsString(ulonglong)) {
        char *endptr;
        unsigned long long int ull = strtoull(ulonglong->valuestring, &endptr, 10);
        printf("IsString. valuestring=\"%s\", unsigned long long int = %llu\n", ulonglong->valuestring, ull);
    }

    /*
    typedef struct __uint256_t { char arr[32]; } __uint256_t;
    hugeint = cJSON_GetObjectItemCaseSensitive(json, "hugeint");
    // Custom integral number interpreter
    __uint256_t value = custom_strtoint(hugeint->valuestring);
    */

    cJSON_Delete(json);

    return 0;
}

Related issues

This issue aims to cover the following ones, which include more details and ideas: