IT评测·应用市场-qidao123.com技术社区

标题: 【C/C++】nlohmann::json从文件读取json,并举行解析打印,实例DEMO [打印本页]

作者: 圆咕噜咕噜    时间: 2025-1-5 00:50
标题: 【C/C++】nlohmann::json从文件读取json,并举行解析打印,实例DEMO
使用 json::parse 函数将JSON格式的字符串解析为 nlohmann::json 对象。这个函数支持多种输入源,包括字符串、文件流等。
  1. #include <iostream>
  2. #include <nlohmann/json.hpp>
  3. #include <fstream>
  4. using json = nlohmann::json;
  5. int main() {
  6.     // 解析 JSON 字符串
  7.     std::string json_str = R"({
  8.         "name": "Alice",
  9.         "age": 30,
  10.         "hobbies": ["reading", "coding", "traveling"]
  11.     })";
  12.     json j = json::parse(json_str);
  13.     // 输出 JSON
  14.     std::cout << j.dump(4) << std::endl;
  15.     // 从文件读取 JSON
  16.     std::ifstream file("data.json");
  17.     if (file.is_open()) {
  18.         json j_file = json::parse(file);
  19.         std::cout << j_file.dump(4) << std::endl;
  20.         file.close();
  21.     }
  22.     return 0;
  23. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/) Powered by Discuz! X3.4