繁体   English   中英

遍历 json 并将 Json 键的第一个字符更改为大写

[英]Iterate over json and change first character of Json keys to upper case

我想要 go 抛出所有 json 键并将第一个字符转换为大写。 我知道我无法更改 json 密钥,因此请从旧密钥中创建一个新的 json

我使用 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]);
        }
    }
}

我的问题是在数组的情况下,我不知道在 arrays 数组或 json 数组的情况下进行递归

对于这个 json

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

预期结果

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

我认为它应该是这样的:

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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM