#include <nlohmann/json.hpp>
#include <iostream>
#include <string>
// 递归函数,用于找到键并修改其对应的值
void
modifyValueByKey(nlohmann::json& j, const std::string& key, const nlohmann::json& new_value)
{
if (j.is_object())
{
for (auto it = j.begin(); it != j.end(); ++it)
{
if (it.key() == key)
{
it.value() = new_value; // 修改找到的键对应的值
return; // 修改完成后返回
}
else if (it.value().is_object() || it.value().is_array())
{
modifyValueByKey(it.value(), key, new_value); // 递归调用
}
}
}
}
int
main()
{
// 给定的 JSON 数据
nlohmann::json j = R"({
"shcool": {
"stduent": {
"kangkang": {
"name": "John",
"age": 30
}
}
}
})"_json;
// 修改 "age" 键的值
modifyValueByKey(j, "age", 31);
// 输出修改后的 JSON 数据
std::cout << "Modified JSON: " << j.dump(4) << std::endl;
// 修改 "kangkang" 键对应的 "name" 的值
modifyValueByKey(j["shcool"]["stduent"]["kangkang"], "name", "Kangkang");
// 输出最终的 JSON 数据
std::cout << "Final JSON: " << j.dump(4) << std::endl;
return 0;
}
修改json数据中的任意key值对应的value值
最新推荐文章于 2024-07-06 00:41:27 发布