akheron / jansson

C library for encoding, decoding and manipulating JSON data
http://www.digip.org/jansson/
Other
3.05k stars 809 forks source link

decode incorrectly for 64 bit integer via json_unpack api #577

Closed jacobkyhsu closed 3 years ago

jacobkyhsu commented 3 years ago

Hi,

when i decode 64 bits integer via json_unpack api, i got a incorrect value, the return value is only 32 bits. so i use another method to get 64 bits integer via json_integer_value, the return value is correct. does json_unpack support to decode 64 bits integer?

follows is my test code.

include

include

include

include "jansson.h"

include "jansson_config.h"

const char data="{\"64bit\":9223372036854775807}"; void main(){ json_t root; json_error_t error; const char key; json_t value; json_int_t bit64_value =0;

root = json_loads(data, 0, &error);
if(!root){
    printf("error:%s\n\n", error.text);
    return;
}
else{
    // for case 1
    bit64_value = 0;
    json_unpack(root, "{s?i}", "64bit", &bit64_value);
    printf("INT64_MAX=%" PRId64 "\n", INT64_MAX);
    printf("print1: bit64_value=%" PRId64 "\n", bit64_value);

    // for case 2
    void *iter = json_object_iter(root);
    bit64_value = 0;
    while(iter){
        key = json_object_iter_key(iter);
        value = json_object_iter_value(iter);
        if(!strcmp(key, "64bit")){
            bit64_value = json_integer_value(value);
            printf("print2: bit64_value = %" PRId64 "\n", bit64_value);
        }

        iter = json_object_iter_next(value, iter);
    }   
}
if(root)
    json_decref(root);
return;

}

the execute result is as follows: INT64_MAX=9223372036854775807 print1: bit64_value=4294967295 print2: bit64_value = 9223372036854775807

gcc version 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04)

is there any problem in my test code? or json_unpack does not support to decode 64 bits integer?

Mephistophiles commented 3 years ago
json_unpack(root, "{s?i}", "64bit", &bit64_value);

You should use I instead of i for json_unpack. From https://jansson.readthedocs.io/en/2.13/apiref.html#parsing-and-validating-values:

For the case with i json_unpack tries to store sizeof(int) bytes to your pointer: https://github.com/akheron/jansson/blob/master/src/pack_unpack.c#L715-L744