gpt4 book ai didi

c++ - 使用 boost C++ 更改 json 值无效

转载 作者:行者123 更新时间:2023-11-30 03:57:27 31 4
gpt4 key购买 nike

我正在尝试更改我的 json 文件中的一些值,但它对 json 文件没有任何影响,即使它打印了我在下面所做的更改。

json文件:

{
"schemaVersion":1,
"array":[
{ //values...
},
{ //the relevant values..
"id":"stackoverflow",
"visible":true,
}
]
}

json文件是有效的我刚刚写了相关的东西。

boost 代码:

boost::property_tree::ptree doc;
string test = dir_path.string();
boost::property_tree::read_json(test, doc);

BOOST_FOREACH(boost::property_tree::ptree::value_type& framePair2, doc.get_child("array")){
if (!framePair2.second.get<std::string>("id").compare("stackoverflow")){
cout << framePair2.second.get<std::string>("id") << endl;
cout << framePair2.second.get<std::string>("visible") << endl;
framePair2.second.put<string>("visible", "false");
cout << framePair2.second.get<std::string>("visible") << endl;
}

输出:

stackoverflow //which is fine
true //which is also fine
false //which is exactly what I changed and need

问题:

json 文件中没有任何变化即使,尽管它通过framePair2.second.put<string>("visible", "false"); 打印了一个成功的变化|我不明白为什么。

它怎么会打印出false呢? 之后 我使用put 方法并且在json 文件中它仍然是true ?我需要保存 json 文件吗?如果是这样,使用 boost 的命令是什么?

如有任何帮助,我们将不胜感激。

谢谢。

最佳答案

是的,您需要保存 JSON 文件。

这里没有“命令”。而是使用一个函数,就像您使用函数 (read_json) 读取它一样:

更新

这是一个示例(从字符串读取,写入 std::cout)。我修复了处理没有 "id" 属性的数组元素的错误。

Live On Coliru

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
#include <sstream>

using namespace boost::property_tree;

std::string const sample = R"(
{
"schemaVersion": 1,
"array": [{
},
{
"id": "stackoverflow",
"visible": true
}]
}
)";

int main() {

ptree doc;
std::istringstream iss(sample);
read_json(iss, doc);

BOOST_FOREACH(ptree::value_type & framePair2, doc.get_child("array")) {
auto id = framePair2.second.get_optional<std::string>("id");
if (id && !id->compare("stackoverflow")) {
std::cout << framePair2.second.get<std::string>("id") << std::endl;
std::cout << framePair2.second.get<std::string>("visible") << std::endl;
framePair2.second.put<std::string>("visible", "false");
std::cout << framePair2.second.get<std::string>("visible") << std::endl;
}
}

write_json(std::cout, doc);
}

输出:

stackoverflow
true
false
{
"schemaVersion": "1",
"array": [
"",
{
"id": "stackoverflow",
"visible": "false"
}
]
}

关于c++ - 使用 boost C++ 更改 json 值无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27967677/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com