DaveGamble / cJSON

Ultralightweight JSON parser in ANSI C
MIT License
10.68k stars 3.21k forks source link

Enhancement: Functions to get object reference to children starting with prefix/suffix #796

Open Fjara-h opened 10 months ago

Fjara-h commented 10 months ago

I am not proficient in C, so I don't know if this is something that can already be done another way. I am dealing with an api that returns objects named with strings like "stream945" and I am creating linked lists of streams as I iterate over them with ->next. However, they can be mixed with other children objects that are not relevant and have different naming.

I wrote the below function and parsed the string:

char* JSON = "{\"id\": { \"number\": 12837 }, \"name\": \"Ken\"}";

Send that cJSON* object and "i" as the string. and it returns only the first level children of root named starting with i, which is just id. If it is within the purview and standards for cJSON, it would be a very nice inclusion, and if reasonable having something to search suffix or just general containing string would be just as useful.

CJSON_PUBLIC(cJSON *) cJSON_GetObjectwithNamePrefix(const cJSON* const object, const char* const string){
    cJSON *a = NULL;

    if(!a || (strlen(string) == 0) || !object)
    {
        return NULL;
    }

    a = cJSON_CreateObject();

    cJSON* objectChild;
    cJSON_ArrayForEach(objectChild, object){
        if(strncmp(string, objectChild->string, strlen(string)) == 0){
            cJSON_AddItemReferenceToObject(a, objectChild->string, objectChild);
        }
    }

    return a;
}

Also, if this code is deemed acceptable, I would be willing to pull request it, I am just not confident in it.