我正在尝试使用boost属性树创建一个JSON数组.
该文件说:"JSON数组被映射到节点的每个元素与空名称的子节点."
所以我想创建一个空名称的属性树,然后调用write_json(...)以获取数组.但是,文档没有告诉我如何创建未命名的子节点.我试过了ptree.add_child("", value),但这会产生:
Assertion `!p.empty() && "Empty path not allowed for put_child."' failed
Run Code Online (Sandbox Code Playgroud)
文档似乎没有解决这一点,至少不能以任何方式解决.有人可以帮忙吗?
我的输入:data.txt
\n\n{\n "target_url":"www.19lou.com/forum-1637-thread-10031471311655793-1-1.html",\n "trespassing_field":{\n "ratetype":5,\n "spider":{\n "prod_name":"name",\n "link_src":1 \n }\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n使用代码:
\n\nboost::property_tree::ptree json_tree;\nboost::property_tree::read_json("data.txt", json_tree);\nstd::stringstream json_main_pack;\nboost::property_tree::write_json(json_main_pack, json_tree);\nLOG(NOTICE) << "json: " << json_main_pack.str();\nRun Code Online (Sandbox Code Playgroud)\n\n输出:
\n\n{\n "target_url": "www.19lou.com\\/forum-1637-thread-10031471311655793-1-1.html",\n "trespassing_field": {\n "ratetype": "5",\n "spider": {\n "prod_name": "name",\n "link_src": "1"\n }\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\nwrite_json()将整数值转换为字符串。它转换"ratetype":5为"ratetype": "5"。这是不正确的。\n如何准确转换\xef\xbc\x9f输入整数值,然后输出整数值。
我正在为Boost属性树编写JSON包装器.目前,重点是将生成的JSON写入字符串或文件.
使用boost :: property_tree :: json_parser :: write_json(ss,*pt)生成的属性树以字符串形式写入.
但是这种方法不理解什么是true,false,null或数字.一切都转换为字符串.
阅读Boost文档,这是库的限制.有没有办法修改这种行为?
我稍微修改了Boost Property Tree,我遇到了这个例子.我需要将最终结果转换为vector,所以我之后又添加了一行
write_json(ss, root);
Run Code Online (Sandbox Code Playgroud)
像这样:
std::vector<char> testVec(std::begin(ss.str()), std::end(ss.str()));
Run Code Online (Sandbox Code Playgroud)
我也试过这个:
std::string someString = ss.str()
char* someArray = (char*)someString.c_str();
std::vector<char> someVec(someArray, someArray+sizeof(someArray));
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,我都收到此错误:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Run Code Online (Sandbox Code Playgroud)
什么提示我做错了什么?我收集的不是属性树的问题.这是字符串到矢量转换的问题.我想这是有道理的,因为向量只应该是一维的,但我不知道如何将该字符串转换为向量并再次将其返回.