0

I want to parse a json data obtain from a server using cJSON, this is how the data looks like

{
  "ID": "2",
  "Success": "Updated"
}

using this code it works fine


int main()
{
    char ptr[] = "{"
                 "\"ID\": \"2\","
                 "\"Success\": \"Updated\""
                 "}";

    cJSON * jsn = cJSON_Parse(ptr);

    if (jsn == NULL) 
        printf("failed to parse json data\n");


    cJSON * id = cJSON_GetObjectItemCaseSensitive(jsn, "ID");
    if (cJSON_IsString(id) )
    {
        printf("Checking monitor \"%s\"\n", id->valuestring);
    }

    return 0;
}

but the code reads the result in a heap allocated buffer and passes it to a function called get_id

int get_id(char * ptr)
{
    printf(">>>%s<<<\n", ptr);
    cJSON * id;
    cJSON *json = cJSON_Parse(ptr);
    if (json == NULL)
    {
        printf("Failed to parse json");
        return 0;
    }
    id = cJSON_GetObjectItemCaseSensitive(json, "ID");
    if (cJSON_IsString(id) )
    {
        printf("Checking monitor \"%s\"\n", id->valuestring);
    }
   
    return 0;
}

this function fails to prase and find the id but outputs the data like so

>>>{
  "ID": "2",
  "Success": "Updated"
}
<<<

I tried to check the code in gdb

(gdb) p id->valuestring
$4 = 0x223e5765d00 "2"
(gdb)   

this shows that the code does parse the json successfully but still it does not output the value using printf

loaded_dypper
  • 262
  • 3
  • 12

0 Answers0