为什么 Boost 属性树 write_json 将所有内容保存为字符串?有可能改变吗? [英] Why does Boost property tree write_json save everything as string? Is it possible to change that?

查看:38
本文介绍了为什么 Boost 属性树 write_json 将所有内容保存为字符串?有可能改变吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 boost 属性树 write_json 进行序列化,它将所有内容保存为字符串,并不是数据错误,但我每次都需要显式转换它们,并且我想在其他地方使用它们.(如在 python 或其他 C++ json(非 boost)库中)

I'm trying to serialize using boost property tree write_json, it saves everything as strings, it's not that data are wrong, but I need to cast them explicitly every time and I want to use them somewhere else. (like in python or other C++ json (non boost) library)

这里是一些示例代码以及我根据语言环境得到的内容:

here is some sample code and what I get depending on locale:

boost::property_tree::ptree root, arr, elem1, elem2;
elem1.put<int>("key0", 0);
elem1.put<bool>("key1", true);
elem2.put<float>("key2", 2.2f);
elem2.put<double>("key3", 3.3);
arr.push_back( std::make_pair("", elem1) );
arr.push_back( std::make_pair("", elem2) );
root.put_child("path1.path2", arr);

std::stringstream ss;
write_json(ss, root);
std::string my_string_to_send_somewhare_else = ss.str();

my_string_to_send_somewhere_else 是……像这样:

and my_string_to_send_somewhere_else is sth. like this:

{
    "path1" :
    {
       "path2" :
       [
            {
                 "key0" : "0",
                 "key1" : "true"
            },
            {
                 "key2" : "2.2",
                 "key3" : "3.3"
            }
       ]
    }
}

无论如何将它们保存为值,例如:"key1" : true 还是 "key2" : 2.2?

Is there anyway to save them as the values, like: "key1" : true or "key2" : 2.2?

推荐答案

我最终在我的工具中添加了另一个函数来解决这个问题:

I ended up adding another function to my utils to solve this:

#include <string>
#include <regex>
#include <boost/property_tree/json_parser.hpp>

namespace bpt = boost::property_tree;
typedef bpt::ptree JSON;
namespace boost { namespace property_tree {
    inline void write_jsonEx(const std::string & path, const JSON & ptree)
    {
        std::ostringstream oss;
        bpt::write_json(oss, ptree);
        std::regex reg("\"([0-9]+\.{0,1}[0-9]*)\"");
        std::string result = std::regex_replace(oss.str(), reg, "$1");

        std::ofstream file;
        file.open(path);
        file << result;
        file.close();
    }
} }

希望有所帮助.

这篇关于为什么 Boost 属性树 write_json 将所有内容保存为字符串?有可能改变吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆