#include <nlohmann/json.hpp> using json = nlohmann::json; json data = { "data": [ { "detail": "system init", "id": "1", "log_type": "0", "module_type": "8", "time": "2023-05-28 05:55:43" }, { "detail": "system init success", "id": "2", "log_type": "0", "module_type": "8", "time": "2023-05-28 05:55:44" }, { "detail": "system init", "id": "3", "log_type": "0", "module_type": "8", "time": "2023-05-28 06:00:41" } ] }; 帮我写一个C++代码把上面的json导出成到txt文本中, 不要用json的形式,帮我人性化处理一下json数据,重新排版
时间: 2023-12-04 13:03:42 浏览: 89
C++ json库 (nlohmann/json)https://github.com/nlohmann/json
好的,请参考以下代码:
```c++
#include <iostream>
#include <fstream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main() {
// json数据
json data = {
"data": [
{
"detail": "system init",
"id": "1",
"log_type": "0",
"module_type": "8",
"time": "2023-05-28 05:55:43"
},
{
"detail": "system init success",
"id": "2",
"log_type": "0",
"module_type": "8",
"time": "2023-05-28 05:55:44"
},
{
"detail": "system init",
"id": "3",
"log_type": "0",
"module_type": "8",
"time": "2023-05-28 06:00:41"
}
]
};
// 打开txt文件
std::ofstream out("data.txt");
// 遍历json数据,将每条数据按照指定格式写入txt文件
for (auto& item : data["data"]) {
out << "id: " << item["id"] << std::endl;
out << "module_type: " << item["module_type"] << std::endl;
out << "log_type: " << item["log_type"] << std::endl;
out << "detail: " << item["detail"] << std::endl;
out << "time: " << item["time"] << std::endl;
out << std::endl;
}
// 关闭文件
out.close();
std::cout << "导出成功!" << std::endl;
return 0;
}
```
这段代码会将json数据按照指定格式写入到data.txt文件中。您可以自定义输出格式,只需要修改遍历json数据的部分即可。
阅读全文