nlohmann json 对索引向量使用 .at() 方法
nlohmann json use the .at() method for a vector of indexes
我使用 nlohmann json 库有一段时间了,但最近发现自己遇到了问题。我有一个对象的索引向量:
vector<string> indexes = {"value1", "subval"}; // etc
我想做这样的事情:
json myObj = "{\"value1\":{}}"_json;
myObj["value1"]["subval"] = "test";
我该怎么做?
我试过这个:
json myObj = "{\"value1\":{}}"_json;
json ref = myObj;
for (string i : indexes) {
ref = ref[i];
}
myObj = ref;
但这不起作用,因为它没有访问嵌套元素,它只是将对象设置为嵌套值。
json ref = myObj;
执行此操作时,您应该意识到 ref 不是引用或指针,无论您想要什么。这是一个副本。
解决方案:尝试改用 reference_wrapper。
vector<string> indexes = {"value1", "subval"};
json myObj;
auto ref = std::ref(myObj);
for (string i : indexes) {
ref = ref.get()[i];
}
ref.get() = "test";
std::cout << myObj << std::endl;
或者代替 reference_wrapper,您也可以使用指针。你的愿望。 json& ref
显然不起作用 - 您不能重新分配引用,因此 reference_wrapper 代替。
我使用 nlohmann json 库有一段时间了,但最近发现自己遇到了问题。我有一个对象的索引向量:
vector<string> indexes = {"value1", "subval"}; // etc
我想做这样的事情:
json myObj = "{\"value1\":{}}"_json;
myObj["value1"]["subval"] = "test";
我该怎么做?
我试过这个:
json myObj = "{\"value1\":{}}"_json;
json ref = myObj;
for (string i : indexes) {
ref = ref[i];
}
myObj = ref;
但这不起作用,因为它没有访问嵌套元素,它只是将对象设置为嵌套值。
json ref = myObj;
执行此操作时,您应该意识到 ref 不是引用或指针,无论您想要什么。这是一个副本。
解决方案:尝试改用 reference_wrapper。
vector<string> indexes = {"value1", "subval"};
json myObj;
auto ref = std::ref(myObj);
for (string i : indexes) {
ref = ref.get()[i];
}
ref.get() = "test";
std::cout << myObj << std::endl;
或者代替 reference_wrapper,您也可以使用指针。你的愿望。 json& ref
显然不起作用 - 您不能重新分配引用,因此 reference_wrapper 代替。