如何在C++中解析jason数据
导读:在 C++ 中解析 JSON 数据,你可以使用第三方库,例如 nlohmann/json 首先,确保你已经安装了 nlohmann/json 库。如果没有,请访问 https://github.com/nlohmann/json#int...
在 C++ 中解析 JSON 数据,你可以使用第三方库,例如 nlohmann/json
-
首先,确保你已经安装了 nlohmann/json 库。如果没有,请访问 https://github.com/nlohmann/json#integration 获取安装说明。
-
包含 json.hpp 头文件:
#include<
iostream>
#include <
fstream>
#include<
string>
#include "json.hpp"
using json = nlohmann::json;
using namespace std;
- 从文件或字符串中读取 JSON 数据:
// 从文件读取 JSON 数据
ifstream ifs("example.json");
json j = json::parse(ifs);
// 从字符串读取 JSON 数据
string json_str = R"({
"name": "John", "age": 30, "city": "New York"}
)";
json j = json::parse(json_str);
- 访问 JSON 数据的值:
// 获取 JSON 对象的键值对
string name = j["name"];
int age = j["age"];
string city = j["city"];
// 获取 JSON 数组的元素
json arr = j["array"];
for (const auto&
elem : arr) {
cout<
<
elem<
<
endl;
}
- 修改 JSON 数据的值:
j["name"] = "Jane";
j["age"] = 25;
- 将 JSON 数据写入文件或字符串:
// 将 JSON 数据写入文件
ofstream ofs("output.json");
ofs <
<
j;
// 将 JSON 数据转换为字符串
string json_str = j.dump();
这是一个完整的示例代码:
#include<
iostream>
#include <
fstream>
#include<
string>
#include "json.hpp"
using json = nlohmann::json;
using namespace std;
int main() {
// 从文件读取 JSON 数据
ifstream ifs("example.json");
json j = json::parse(ifs);
// 访问 JSON 数据的值
string name = j["name"];
int age = j["age"];
string city = j["city"];
// 修改 JSON 数据的值
j["name"] = "Jane";
j["age"] = 25;
// 将 JSON 数据写入文件
ofstream ofs("output.json");
ofs <
<
j;
return 0;
}
在这个示例中,我们从名为 example.json
的文件中读取 JSON 数据,访问其中的值,修改它们,然后将修改后的 JSON 数据写入名为 output.json
的文件。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: 如何在C++中解析jason数据
本文地址: https://pptw.com/jishu/699362.html