3

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 }

Kavitha K T
  • 119
  • 8

2 Answers2

2

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);
Jing Qiu
  • 533
  • 4
  • 11
  • Actually, calling _del isn't needed. The _add call will replace any previous field value, even if the new value is NULL. – Eric Mar 11 '19 at 03:34
0

The library has a method to set a null value. https://github.com/json-c/json-c/blob/master/json_object.h#L1000

You can add the value as

json_object_object_add(json_object, "nullable_field", json_object_new_null());

As result, you will have:

{
    ...
    "nullable_field":null,
    ...
}
Jairo Reyes
  • 3
  • 1
  • 4