将json代码格式化为std::string

Format json code into std::string

本文关键字:std string 格式化 json 代码      更新时间:2023-10-16

这是一个初学者问题,如何将以下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" : 0n"
"  },n"
"  {n"
"    "x" : 640,n"
"    "y" : 0,n"
"    "z" : 0n"
"  },n"
"  {n"
"    "x" : 640,n"
"    "y" : 0,n"
"    "z" : 480n"
"  },n"
"  {n"
"    "x" : 0,n"
"    "y" : 0,n"
"    "z" : 480n"
"  }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.1n"
"  },n"
"  {n"
"    "x" : 12.1,n"
"    "y" : 12.1,n"
"    "z" : 12.1n"
"  },n" 
"  {n"
"    "x" : 12.1,n"
"    "y" : 12.1,n"
"    "z" : 12.1n"
"  },n"
"  {n"
"    "x" : 12.1,n"
"    "y" : 12.1,n"
"    "z" : 12.1n"
"  }n"
"]n";