From 503e8b3c65cbc82162d52a6fd57ebb8164a246fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Bollo?= Date: Tue, 12 Oct 2021 14:32:04 +0200 Subject: [PATCH] DRAFT PROPOSAL - Add option JSON_C_OBJECT_ADD_IF_NOT_NULL This option of json_object_object_add_ex will cancel the addition if the added value is NULL. Remarks: - testing value with json_object_is_type(val, json_type_null) could make sense - that commit introduces a new test that could slow the speed of add --- json_object.c | 3 +++ json_object.h | 5 +++++ 2 files changed, 8 insertions(+) diff --git a/json_object.c b/json_object.c index 9df5809..3fc6b97 100644 --- a/json_object.c +++ b/json_object.c @@ -591,6 +591,9 @@ int json_object_object_add_ex(struct json_object *jso, const char *const key, assert(json_object_get_type(jso) == json_type_object); + if (val == NULL && (opts & JSON_C_OBJECT_ADD_IF_NOT_NULL)) + return 0; + // We lookup the entry and replace the value, rather than just deleting // and re-adding it, so the existing key remains valid. hash = lh_get_hash(JC_OBJECT(jso)->c_object, (const void *)key); diff --git a/json_object.h b/json_object.h index d67f384..0b3f9f1 100644 --- a/json_object.h +++ b/json_object.h @@ -103,6 +103,11 @@ extern "C" { * JSON_C_OBJECT_KEY_IS_CONSTANT); */ #define JSON_C_OBJECT_KEY_IS_CONSTANT (1 << 2) +/** + * A flag for the json_object_object_add_ex function which + * cancel the add if the value is NULL. + */ +#define JSON_C_OBJECT_ADD_IF_NOT_NULL (1 << 3) /** * Set the global value of an option, which will apply to all