Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions cJSON.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
6 changes: 5 additions & 1 deletion cJSON.h
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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);

Expand Down