RepidJson将内容格式化后写入文件

以下是使用RapidJson将JSON内容格式化后写入文件的示例代码:

cpp 复制代码
#include <iostream>
#include <fstream>
#include <string>
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/writer.h"

using namespace rapidjson;

int main() {
    // 创建JSON文档
    Document doc;
    doc.SetObject();

    // 添加一些键值对
    Value name("John Doe");
    Value age(30);
    Value hobbies(kArrayType);
    hobbies.PushBack("Programming", doc.GetAllocator());
    hobbies.PushBack("Reading", doc.GetAllocator());
    hobbies.PushBack("Playing guitar", doc.GetAllocator());

    doc.AddMember("name", name, doc.GetAllocator());
    doc.AddMember("age", age, doc.GetAllocator());
    doc.AddMember("hobbies", hobbies, doc.GetAllocator());

    // 格式化JSON内容
    StringBuffer buffer;
    PrettyWriter<StringBuffer> writer(buffer);
    doc.Accept(writer);

    // 将JSON内容写入文件
    std::string filename = "example.json";
    std::ofstream ofs(filename);
    if (ofs.is_open()) {
        ofs << buffer.GetString();
        ofs.close();
        std::cout << "JSON content has been written to " << filename << std::endl;
    } else {
        std::cerr << "Failed to open file " << filename << std::endl;
    }

    return 0;
}

在上面的示例代码中,我们使用Document类创建了一个JSON文档,并使用AddMember()方法添加了几个键值对。然后,我们使用PrettyWriter类将JSON内容格式化为漂亮的字符串,并将其写入example.json文件中。你可以根据你的需要修改键值对的值,或者在JSON文档中添加、删除或修改键值对。

相关推荐
网络研究院14 天前
由于安全风险,安全领导者考虑禁止人工智能编码
人工智能·安全·开源·开发·风险·技术·代码
京东零售技术25 天前
《代码整洁之道》-大师眼中的整洁代码是什么样
后端·代码
York19961 个月前
如何使用python格式化大的json文件
vscode·python·json·文件·格式化
文心快码 Baidu Comate1 个月前
文心快码 Baidu Comate 前端工程师观点分享:以文心快码 Baidu Comate为例,智能代码助手需要什么(一)
人工智能·ai编程·代码·文心快码·智能编程助手
程序员鱼皮2 个月前
网易云音乐故障 2 小时,这次到底谁背锅?(今天记得领补偿)
前端·后端·计算机·程序员·互联网·编程·代码
Fulin_Gao2 个月前
【多模态大模型】LLaMA in arXiv 2023
llama·原理·代码·rope·rmsnorm·swiglu·flashattention
cxylay2 个月前
【matlab版】如何利用代码计算声音信号的声压级
开发语言·matlab·代码·波形图·声压·声压级·声压级图
程序员鱼皮2 个月前
总有坏人想爬我网站的数据,看我用这 10 招干他!
计算机·程序员·编程·网站·代码·自学·编程经验
程序员鱼皮2 个月前
一下午连续故障两次,谁把我们接口堵死了?!
前端·后端·计算机·程序员·编程·项目·代码·编程经验
程序员鱼皮2 个月前
学了十几种编程语言后,我终于悟了!
java·计算机·编程·代码·编程经验·自学编程