Note-c how to iterate over keys of an object?

Are there any examples of how to iterate over keys and values of a JSON object?

I have tried this:

    // iterate over the keys
    J* key;
    JObjectForEach(name, cmd.params) {
        const char* keyname = JGetStringValue(key);
        J* value = JGetObjectItem(cmd.params, keyname);
        ...
    }

However, this doesn’t work, since const char* key = JGetStringValue(name); returns nullptr. This is because JGetStringValue is expecting (as you might guess from the name) a string value.

Internally, the J struct has a stringvalue pointer for true string values, and string for key names.

I could just use key->string to get the key name, but this is going behind the scenes. Is there an officially supported way to do this?

Hi @devElert,

You should be able to iterate over your JSON with this:

J *field = NULL;
JObjectForEach(field, object) {
    char *value = JStringValue(field);
    const char *key = JGetItemName(field);
}
2 Likes

Awesome, thanks! That’s perfect.

2 Likes