如何使用C++(nlohmann库)向JSON文件添加新用户数据?
用nlohmann json向Infos数组添加新用户的实现方法
核心步骤
- 读取现有JSON文件到
nlohmann::json对象中 - 构造包含
name、age、tel、mail的新用户JSON对象 - 将新用户对象追加到
Infos数组末尾 - 将修改后的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
相关产品推荐
相关产品推荐

