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 对象。这个函数支持多种输入源,包括字符串、文件流等。
#include <iostream>
#include <nlohmann/json.hpp>
#include <fstream>
using json = nlohmann::json;
int main() {
// 解析 JSON 字符串
std::string json_str = R"({
"name": "Alice",
"age": 30,
"hobbies": ["reading", "coding", "traveling"]
})";
json j = json::parse(json_str);
// 输出 JSON
std::cout << j.dump(4) << std::endl;
// 从文件读取 JSON
std::ifstream file("data.json");
if (file.is_open()) {
json j_file = json::parse(file);
std::cout << j_file.dump(4) << std::endl;
file.close();
}
return 0;
}
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/)
Powered by Discuz! X3.4