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

时间:2015-01-15 16:02:27

标签: c++ json boost edit savechanges

我正在尝试更改json文件中的某些值,但它在json文件中没有任何效果,即使它打印出我在下面所做的更改。

json文件:

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

json文件有效我刚刚写了相关内容。

提升代码:

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");打印成功更改,我不明白为什么。

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

任何帮助都将不胜感激。

谢谢。

2 个答案:

答案 0 :(得分:1)

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

没有&#34;命令&#34;为了这。而是像使用一个(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"
        }
    ]
}

答案 1 :(得分:1)

解决方案:

  • Boost的json解析器仅在ptree中使用字符串,这意味着ptree没有对bool / int等类型的引用。只有字符串。
  • 虽然我使用的不是那么优雅的解决方案,比如使用ifstream和ofstream类进行普通文件操作,here你可以找到(向下滚动到C / C ++部分)所有支持类型的json API