Home > Enterprise >  Iterate over json and change first character of Json keys to upper case
Iterate over json and change first character of Json keys to upper case

Time:09-08

I want go throw all json keys and convert the first character to upper case. i understand that i cant change json keys so crate a new json from the old one

i using json::Value,

void change_keys(Json::Value& oldJson, Json::Value& newJson) {
    for (Json::ValueConstIterator it = oldJson.begin(); it != oldJson.end();   it) {
        std::string newKey = it.name();
        newKey[0] = std::toupper(newKey[0]);
        newJson[newKey] = oldJson[it.name()];
        if (it->isArray()) {
            return;
        }
        if (it->isObject()) {
            change_keys(oldJson[it.name()],newJson[newKey]);
        }
    }
}

My problem is in case of array, i don't know to proceed the recursive in case of array of arrays or array of json

for this json

{"result": {
            "main": [
                {
                    "free": 0,
                    "total": 0
                }
             ]
         }

expected restult

{"Result": {
            "Main": [
                {
                    "Free": 0,
                    "Total": 0
                }
             ]
         }

CodePudding user response:

I think it should be something like:

void change_keys(Json::Value& oldJson, Json::Value& newJson) {
    if (oldJson.isObject()) {
        for (Json::ValueConstIterator it = oldJson.begin(); it != oldJson.end();   it) {
            std::string newKey = it.name();
            newKey[0] = std::toupper(newKey[0]);
            change_keys(oldJson[it.name()], newJson[newKey])
        }
    } else if (oldJson.isArray()) {
        for (int i = 0; i != oldJson.size();   i) {
            newJson.append(Json::nullValue);
            change_keys(oldJson[i], newJson[i]);
        }
    } else {
        newJson = oldJson;
    }
}
  • Related