Search code examples
json-c

How can I add null values in JSONC?


I am using JSONC library in c to create json. But I can't create null values. How can I create the following json data using JSONC library? {"status" : null }


Solution

  • According to the interface of json-c library, I think you can delete the nameval pair first from the object, and then add a field with NULL as val:

    json_object_object_del(jexample, "status");
    json_object_object_add(jexample, "status", NULL);
    

    Reference: https://github.com/json-c/json-c/blob/master/json_object.h

    See API definition:

    /*
     * @param obj the json_object instance
     * @param key the object field name (a private copy will be duplicated)
     * @param val a json_object or NULL member to associate with the given field
     *
     * @return On success, <code>0</code> is returned.
     *  On error, a negative value is returned.
     */
        JSON_EXPORT int json_object_object_add(struct json_object* obj, const char *key,
                           struct json_object *val);