gpt4 book ai didi

c++ - 使用 Boost ptree 将 JSON 数组解析为 std::string

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:14:27 25 4
gpt4 key购买 nike

我有这段代码,我需要解析/或获取 JSON 数组作为 std::string 以在应用程序中使用。

std::string ss = "{ \"id\" : \"123\", \"number\" : \"456\", \"stuff\" : [{ \"name\" : \"test\" }] }";

ptree pt2;
std::istringstream is(ss);
read_json(is, pt2);
std::string id = pt2.get<std::string>("id");
std::string num= pt2.get<std::string>("number");
std::string stuff = pt2.get<std::string>("stuff");

需要的是像这样检索的“东西” std::string [{ "name": "test"}]

但是 stuff 上面的代码只是返回空字符串。可能有什么问题

最佳答案

数组表示为具有许多 "" 键的子节点:

docs

  • JSON arrays are mapped to nodes. Each element is a child node with an empty name. If a node has both named and unnamed child nodes, it cannot be mapped to a JSON representation.

Live On Coliru

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

using boost::property_tree::ptree;

int main() {
std::string ss = "{ \"id\" : \"123\", \"number\" : \"456\", \"stuff\" : [{ \"name\" : \"test\" }, { \"name\" : \"some\" }, { \"name\" : \"stuffs\" }] }";

ptree pt;
std::istringstream is(ss);
read_json(is, pt);

std::cout << "id: " << pt.get<std::string>("id") << "\n";
std::cout << "number: " << pt.get<std::string>("number") << "\n";
for (auto& e : pt.get_child("stuff")) {
std::cout << "stuff name: " << e.second.get<std::string>("name") << "\n";
}
}

打印

id:     123
number: 456
stuff name: test
stuff name: some
stuff name: stuffs

关于c++ - 使用 Boost ptree 将 JSON 数组解析为 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31345401/

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