gpt4 book ai didi

c++ - 使用 JSON Spirit 进行 pretty-print

转载 作者:行者123 更新时间:2023-11-30 05:07:45 26 4
gpt4 key购买 nike

我的 C++ 程序收到一个长(数千个符号)的 JSON 字符串,我想使用 JSON Spirit(用于调试)打印多行、右缩进等。例如:

{
"abc": "def",
"xyz":
[
"pqr": "ijk"
]
}

等等。我尝试了 write 函数:

const json_spirit::Value val("...long JSON string here ...");
cout << json_spirit::write(val, json_spirit::pretty_print) << endl;

但在原始字符串中只得到了额外的反斜杠。

你能告诉我怎么做吗?

最佳答案

您获得原始输入字符串的原因是因为您将字符串直接分配给 json_spirit::Value。您需要做的是让 json_spirit 解析字符串。

下面的 C++11 代码给出了预期的输出:

#include <json_spirit/json_spirit.h>
#include <ostream>
#include <string>

int main() {
std::string const inputStr =
R"raw({ "abc": "def", "xyz": [ "pqr": "ijk" ] })raw";

json_spirit::Value inputParsed;
json_spirit::read(inputStr, inputParsed);

std::cout
<< json_spirit::write(inputParsed, json_spirit::pretty_print) << "\n";
}

旁注:有一大堆更轻量级的 C++ JSON 库(即不需要 Boost),以防您感兴趣。我个人用过nlohmann's json这只需要一个头文件。 RapidJSON似乎也是一个很好的选择。可以在 nativejson-benchmark 上找到 40 多个 C++ JSON 库的大量基准测试页面。

关于c++ - 使用 JSON Spirit 进行 pretty-print ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47163586/

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