diff --git a/cJSON.c b/cJSON.c index 88c2d95b3..c92c8cb11 100644 --- a/cJSON.c +++ b/cJSON.c @@ -1919,6 +1919,41 @@ CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) return (int)size; } +/* + Returns all keys of an object as a cJSON string array. The caller is responsible + for freeing the returned array with cJSON_Delete. Returns NULL on invalid input + or allocation failure. +*/ +CJSON_PUBLIC(cJSON *) cJSON_GetAllKeys(const cJSON *const object) +{ + if (object == NULL || !(object->type & cJSON_Object)) + { + return NULL; + } + + cJSON *array = cJSON_CreateArray(); + if (array == NULL) + { + return NULL; + } + + cJSON *child = object->child; + while (child) + { + char *key = child->string; + cJSON *newItem = cJSON_CreateString(key); + if (newItem == NULL) + { + cJSON_Delete(array); + return NULL; + } + cJSON_AddItemToArray(array, newItem); + + child = child->next; + } + return array; +} + static cJSON* get_array_item(const cJSON *array, size_t index) { cJSON *current_child = NULL; diff --git a/cJSON.h b/cJSON.h index cab5feb42..ea57eb8ea 100644 --- a/cJSON.h +++ b/cJSON.h @@ -172,6 +172,10 @@ CJSON_PUBLIC(void) cJSON_Delete(cJSON *item); /* Returns the number of items in an array (or object). */ CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); + +/* Returns an array of all keys in an object as cJSON strings. Returns NULL if object is not an object or is NULL. Caller must free the result with cJSON_Delete. */ +CJSON_PUBLIC(cJSON *) cJSON_GetAllKeys(const cJSON *const object); + /* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); /* Get item "string" from object. Case insensitive. */ @@ -261,7 +265,7 @@ CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); /* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings. - * The input pointer json cannot point to a read-only address area, such as a string constant, + * The input pointer json cannot point to a read-only address area, such as a string constant, * but should point to a readable and writable address area. */ CJSON_PUBLIC(void) cJSON_Minify(char *json);