gpt4 book ai didi

c++ - 将 json 代码格式化为 std::string

转载 作者:行者123 更新时间:2023-11-27 22:43:48 24 4
gpt4 key购买 nike

这是一个初学者问题,我如何将以下 json 字符串数组格式化为 std::string

[
{
"x" : 12.1,
"y" : 12.1,
"z" : 12.1
},
{
"x" : 12.1,
"y" : 12.1,
"z" : 12.1
},
{
"x" : 12.1,
"y" : 12.1,
"z" : 12.1
},
{
"x" : 12.1,
"y" : 12.1,
"z" : 12.1
}
]

这里是json字符串

const std::string json =
"[\n"
" {\n"
" \"x\" : 0,\n"
" \"y\" : 0,\n"
" \"z\" : 0\n"
" },\n"
" {\n"
" \"x\" : 640,\n"
" \"y\" : 0,\n"
" \"z\" : 0\n"
" },\n"
" {\n"
" \"x\" : 640,\n"
" \"y\" : 0,\n"
" \"z\" : 480\n"
" },\n"
" {\n"
" \"x\" : 0,\n"
" \"y\" : 0,\n"
" \"z\" : 480\n"
" }\n"
"]\n";


Json::Value coordinates;
Json::Reader reader;

reader.parse( json, coordinates );

所以我试图解析上面的 json 数组,以获取坐标列表,但无法正确解析。

最佳答案

从 C++11 开始,您可能会使用原始字符串:

const std::string json = R"(
[
{
"x" : 12.1,
"y" : 12.1,
"z" : 12.1
},
{
"x" : 12.1,
"y" : 12.1,
"z" : 12.1
},
{
"x" : 12.1,
"y" : 12.1,
"z" : 12.1
},
{
"x" : 12.1,
"y" : 12.1,
"z" : 12.1
}
]
)";

之前,你必须做一些转义,如 " -> \":

const std::string json = 
"[\n"
" {\n"
" \"x\" : 12.1,\n"
" \"y\" : 12.1,\n"
" \"z\" : 12.1\n"
" },\n"
" {\n"
" \"x\" : 12.1,\n"
" \"y\" : 12.1,\n"
" \"z\" : 12.1\n"
" },\n"
" {\n"
" \"x\" : 12.1,\n"
" \"y\" : 12.1,\n"
" \"z\" : 12.1\n"
" },\n"
" {\n"
" \"x\" : 12.1,\n"
" \"y\" : 12.1,\n"
" \"z\" : 12.1\n"
" }\n"
"]\n";

关于c++ - 将 json 代码格式化为 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45956081/

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