4

我是 C++ 的新手并尝试使用 nlohmann 库,但我很困惑。我想从 json 修改对象数组。

json = 
{
    "a": "xxxx",
    "b": [{
        "c": "aaa",
        "d": [{
                "e": "yyy"
            },
            {
                "e": "sss",
                "f": "fff"
            }
        ]
    }]
}

现在我想e用上述结构中的“示例”替换值。有人可以帮我吗。

我试图循环遍历 json 结构并能够读取“e”值但无法替换它。我试过了:`

std::vector<std::string> arr_value;
std::ifstream in("test.json");
json file = json::parse(in);

for (auto& td : file["b"])
    for (auto& prop : td["d"])
        arr_value.push_back(prop["e"]);
        //std::cout<<"prop" <<prop["e"]<< std::endl;

for (const auto& x : arr_value)
    std::cout <<"value in vector string= " <<x<< "\n";

for (decltype(arr_value.size()) i = 0; i <= arr_value.size() - 1; i++)
{
    std::string s = arr_value[i]+ "emp";
    std::cout <<"changed value= " <<s << std::endl;
    json js ;
    js = file;
    std::ofstream out("test.json");
    js["e"]= s;
    out << std::setw(4) << js << std::endl;

}
4

1 回答 1

5

以下附加MODIFIED到每个“e”值并将结果写入test_out.json

#include <vector>
#include <iostream>
#include <fstream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
        std::ifstream in("test.json");
        json file = json::parse(in);

        for (auto& td : file["b"])
                for (auto& prop : td["d"]) {
                        prop["e"] = prop["e"].get<std::string>() + std::string(" MODIFIED");
                }

        std::ofstream out("test_out.json");
        out << std::setw(4) << file << std::endl;
}

prop["e"] = ...条线做了三件事:

  • 它使用 key 获取属性"e"
  • .get<std::string>()使用和appends 将其强制转换为字符串"modified",并且
  • 将结果写回到prop["e"],这是对嵌套在 JSON 结构中的对象的引用。
于 2020-01-29T16:25:27.470 回答