You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用C++(nlohmann库)向JSON文件添加新用户数据?

用nlohmann json向Infos数组添加新用户的实现方法

核心步骤

  1. 读取现有JSON文件到nlohmann::json对象中
  2. 构造包含name、age、tel、mail的新用户JSON对象
  3. 将新用户对象追加到Infos数组末尾
  4. 将修改后的JSON写回原文件(或新文件)

完整代码示例

假设你已经有获取用户输入的代码,以下是完整的添加逻辑:

#include <nlohmann/json.hpp>
#include <fstream>
#include <string>
#include <iostream>
#include <iomanip>

using json = nlohmann::json;

// 模拟用户输入获取(替换成你已有的输入逻辑即可)
void getUserInput(std::string& name, int& age, std::string& tel, std::string& mail) {
    std::cout << "用户名: ";
    std::cin >> name;
    std::cout << "年龄: ";
    std::cin >> age;
    std::cout << "电话: ";
    std::cin >> tel;
    std::cout << "邮箱: ";
    std::cin >> mail;
}

int main() {
    // 读取现有JSON文件,若不存在则初始化空数组
    json j;
    std::ifstream inputFile("user_info.json");
    if (inputFile.is_open()) {
        inputFile >> j;
        inputFile.close();
    } else {
        // 文件不存在时创建根结构,包含空的Infos数组
        j = {{"Infos", json::array()}};
    }

    // 获取输入并构造新用户对象
    std::string name, tel, mail;
    int age;
    getUserInput(name, age, tel, mail);

    json newUser = {
        {"name", name},
        {"age", age},
        {"tel", tel},
        {"mail", mail}
    };

    // 追加到Infos数组
    j["Infos"].push_back(newUser);

    // 写回文件,std::setw(4)用于格式化输出,提升可读性
    std::ofstream outputFile("user_info.json");
    outputFile << std::setw(4) << j;
    outputFile.close();

    return 0;
}

注意事项

  • 如果你的JSON结构不是根节点直接包含Infos数组,比如是{"data": {"Infos": [...]}},需要调整访问路径为j["data"]["Infos"].push_back(newUser)
  • 确保文件读写权限正常,避免因权限问题导致操作失败
  • 若年龄字段需要存储为字符串类型,只需把int age改为std::string age即可适配

内容的提问来源于stack exchange,提问作者n0vember

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 17:54:55