更改 json 值对使用提升C++没有影响

Changing json values has no effect using boost C++

本文关键字:C++ 有影响 json 更改      更新时间:2023-10-16

我正在尝试更改 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"); 打印成功更改,json 文件中也没有更改,我不明白为什么。

为什么在我使用 put 方法它打印false并且在 json 文件中它仍然true?我需要保存 json 文件吗?如果是这样,使用它的命令是什么 提升 ?

任何帮助将不胜感激。

谢谢。

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

对此没有"命令"。而是使用一个函数,就像你使用一个(read_json)来读取它一样:

  • http://www.boost.org/doc/libs/1_57_0/doc/html/boost/property_tree/json_parser/write_json_idp202532560.html

更新

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

住在科里鲁

#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"
        }
    ]
}

解决方案:

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