Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
访问C++中的JSON数组值 我是C++新手,想使用NLHHMAN库,我很难理解。我想修改json中的对象数组 json = { "a": "xxxx", "b": [{ "c": "aaa", "d": [{ "e": "yyy" }, { "e": "sss", "f": "fff" } ] }] }_C++_Nlohmann Json - Fatal编程技术网

访问C++中的JSON数组值 我是C++新手,想使用NLHHMAN库,我很难理解。我想修改json中的对象数组 json = { "a": "xxxx", "b": [{ "c": "aaa", "d": [{ "e": "yyy" }, { "e": "sss", "f": "fff" } ] }] }

访问C++中的JSON数组值 我是C++新手,想使用NLHHMAN库,我很难理解。我想修改json中的对象数组 json = { "a": "xxxx", "b": [{ "c": "aaa", "d": [{ "e": "yyy" }, { "e": "sss", "f": "fff" } ] }] },c++,nlohmann-json,C++,Nlohmann Json,现在,我想用上述结构中的示例替换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&

现在,我想用上述结构中的示例替换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;

}
以下内容将修改后的内容附加到每个e值,并将结果写入test_out.json:

道具[e]=。。。line做了三件事:

它获取键为e的属性, 使用.get和appends modified将其强制为字符串,然后 将结果写回prop[e],这是对JSON结构中嵌套的对象的引用。
请显示您正在创建新js的代码,并在新json对象上将e设置为s。当你试图修改原始json文件时会发生什么?是的,你是对的,它只会创建新的e值,而我无法修改原始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;
}