Need help re-sorting some cJSON elements (WiFi credentials)

Hello community, I don’t normally post new topics, but I really need some help, and I hope that you can support me to solve this issue which I have severals days trying to fix it out.

What I want: a function to write WiFi new credentials in JSON list format. If the credentials does not exist, it will just add a new item to the JSON object and save, else if exist it will replace it (in case that the password changes). Also it should re-sort or re-arrange the credentials, giving more priority to the credentials comming as parameters to the function, where 0 is the lowest priority and 10 (or more depending of the limit that I set in a future) is the highest priority to connect to. I’m using NVS to store these parameters as JSON strings.

The problem: The function works well until it needs to re-sort an existing credential, for example:

Before adding a new password to the list, I have these values stored in the flash

{
    "0":  {
        "ssid":   "random",
        "password":   "access1234"
    },
    "1":  {
        "ssid":   "HELLO",
        "password":   "takemypassword"
    }
}

After trying to update HELLO ssid, the JSON string is stored like this:

{
    "0":  {
        "ssid":   "random",
        "password":   "access1234"
    },
    "1":  {
        "ssid":   "HELLO",
        "password":   "takemypassword"
    },
    "1":  {
        "ssid":   "HELLO",
        "password":   "donttakeitplease"
    }
}

The piece of code is attached to this post (you can try it out in your ESP32 Arduino or ESP-IDF after some minimal changes to run the code in that environment) and is ready to simulate that issue on your end if you want to try.

The problem is in the sorting algorithm and between line 148-172, and the replacing credentials implementation ends at 191. After some deep debugging in the code, I think I found the source problem at line 156 where I try to get an specific object from creds_list_json within a for loop() to sort the old credentials in a new JSON object, and after that I’m adding the comming credentials to the highest position.

For some reason I think that I’m using wrong the cJSON_AddItemToObject() and cJSON_GetObjectItem() since it returns not only one credentials in the object, but two. and that’s why when I try to add the comming credentials to the highest index number, it repeats. The expected JSON value should be:

{
    "0":  {
        "ssid":   "random",
        "password":   "access1234"
    },
    "1":  {
        "ssid":   "HELLO",
        "password":   "donttakeitplease"
    }
}

I hope that you can support me on this, I feel that I’m using wrongly the cJSON tool and I hope that you could advice me on what to do to make that sorting successfully.

Kind regards,
Antonio M.

test_code_2.ino (9.75 KB)