json_object_put example validation

525 views
Skip to first unread message

Sriram Iyyappan Mamandoor Pandurangan

unread,
Dec 10, 2021, 4:28:05 AM12/10/21
to json-c
Hi, 

In below example, i see both json_object_put is called for both Object and CpObject. 

Is that fine? Can we avoid calling json_object_put for CpObject?

regards,
Sriram I


#include <json-c/json.h>
#include <stdio.h>
#include <unistd.h>
#include <mcheck.h>

int main()
{
    setenv("MALLOC_TRACE", "output_file_name", 1);
    mtrace();

    struct json_object *Object =     json_object_new_object();
    struct json_object *CpObject =   json_object_new_object();
    struct json_object *CpArray =    json_object_new_array();

    json_object_object_add(Object, "Time",      json_object_new_string("yyyy_mm_dd"));
    json_object_object_add(Object, "Name",      json_object_new_string("123"));
    json_object_object_add(Object, "Action",    json_object_new_string("456"));

    json_object_object_add(CpObject, "Code", json_object_new_string("11"));
    json_object_object_add(CpObject, "Type",     json_object_new_string("22"));
    json_object_object_add(CpObject, "SubType",  json_object_new_string("33"));

    json_object_array_add(CpArray, CpObject);

    json_object_object_add(Object, "CpCommands", CpArray);

    printf ("%s\n",json_object_to_json_string(Object));

    //free memory
    json_object_put(Object);
    json_object_put(CpObject);
}

Eric Hawicz

unread,
Dec 10, 2021, 11:16:53 AM12/10/21
to jso...@googlegroups.com
You add CpObject to CpArray, and CpArray to Object, so the only json_object that you need to call json_object_put() on is Object because it contains the other two.

On Fri, Dec 10, 2021, 4:28 AM Sriram Iyyappan Mamandoor Pandurangan <srirami...@gmail.com> wrote:
Hi, 

In below example, i see both json_object_put is called for both Object and CpObject. 

Is that fine? Can we avoid calling json_object_put for CpObject?

regards,
Sriram I

...


    struct json_object *Object =     json_object_new_object();
    struct json_object *CpObject =   json_object_new_object();
    struct json_object *CpArray =    json_object_new_array();

...

Reply all
Reply to author
Forward
0 new messages