c++ - 在C++中访问json数组值

标签 c++ nlohmann-json

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

json = 
{
    "a": "xxxx",
    "b": [{
        "c": "aaa",
        "d": [{
                "e": "yyy"
            },
            {
                "e": "sss",
                "f": "fff"
            }
        ]
    }]
}
现在,我想在上述结构中将e值替换为“example”。有人可以帮我吗。
我试图遍历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;

}

最佳答案

以下内容将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"] = ...行执行以下三项操作:
  • 通过键"e"
  • 获取属性
  • 使用.get<std::string>()将其强制为字符串,并附加"modified"
  • 将结果写回到prop["e"],它是对嵌套在JSON结构中的对象的引用。
  • 关于c++ - 在C++中访问json数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59970286/

    相关文章:

    c++ - vector 迭代器不可取消引用( vector 内 vector )

    c++ - 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的 vector ?

    c++ - 如何读取 C++ 中的 JSON 内容?

    c++ nlohmann json - 如何测试嵌套对象是否存在或为空

    c++ - 如何在 Visual C++ 中使用 Windows 窗体创建特定控件?

    c++ - 使用 OpenCV 计算 X 和 Y 导数的绝对值

    c++ - C++ 中的表达式

    c++ - 使用 "JSON for Modern C++"库检测整数不适合指定类型?

    c++ - Nlohmann json 获取类型推导

    c++ - 低版本gcc使用的静态库