diff --git a/cJSON.c b/cJSON.c index 3cdc8fa..29e5dbf 100644 --- a/cJSON.c +++ b/cJSON.c @@ -1995,6 +1995,19 @@ CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item) return add_item_to_array(array, item); } +/** Create object and add it to array */ +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToArray(cJSON * const array) +{ + cJSON *object = cJSON_CreateObject(); + if (cJSON_AddItemToArray(array, object)) + { + return object; + } + + cJSON_Delete(object); + return NULL; +} + #if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) #pragma GCC diagnostic push #endif diff --git a/cJSON.h b/cJSON.h index b5ceb29..1fbcca8 100644 --- a/cJSON.h +++ b/cJSON.h @@ -271,6 +271,10 @@ CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * con CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name); +/* Helper function to create an object and add it to an existing array. + * It returns the added object or NULL on failure. */ +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToArray(cJSON * const array); + /* When assigning an integer value, it needs to be propagated to valuedouble too. */ #define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) /* helper for the cJSON_SetNumberValue macro */ diff --git a/tests/cjson_add.c b/tests/cjson_add.c index 00ffc34..7cb69fa 100644 --- a/tests/cjson_add.c +++ b/tests/cjson_add.c @@ -378,6 +378,36 @@ static void cjson_add_array_should_fail_on_allocation_failure(void) cJSON_Delete(root); } +static void cJSON_add_object_to_array_should_add_object(void) +{ + cJSON *root = cJSON_CreateArray(); + cJSON *object = NULL; + + TEST_ASSERT_NOT_NULL(object = cJSON_AddObjectToArray(root)); + TEST_ASSERT_EQUAL_INT(cJSON_GetArraySize(root), 1); + TEST_ASSERT_EQUAL_INT(cJSON_GetArrayItem(root, 0)->type, cJSON_Object); + + cJSON_Delete(root); +} + +static void cjson_add_object_to_array_should_fail_with_null_pointers(void) +{ + TEST_ASSERT_NULL(cJSON_AddObjectToArray(NULL)); +} + +static void cjson_add_object_to_array_should_fail_on_allocation_failure(void) +{ + cJSON *root = cJSON_CreateArray(); + + cJSON_InitHooks(&failing_hooks); + + TEST_ASSERT_NULL(cJSON_AddObjectToArray(root)); + + cJSON_InitHooks(NULL); + + cJSON_Delete(root); +} + int CJSON_CDECL main(void) { UNITY_BEGIN(); @@ -418,5 +448,9 @@ int CJSON_CDECL main(void) RUN_TEST(cjson_add_array_should_fail_with_null_pointers); RUN_TEST(cjson_add_array_should_fail_on_allocation_failure); + RUN_TEST(cJSON_add_object_to_array_should_add_object); + RUN_TEST(cjson_add_object_to_array_should_fail_with_null_pointers); + RUN_TEST(cjson_add_object_to_array_should_fail_on_allocation_failure); + return UNITY_END(); }