温馨提示×

如何在C++中解析jason数据

c++
小樊
81
2024-09-14 10:24:55
栏目: 编程语言

在 C++ 中解析 JSON 数据,你可以使用第三方库,例如 nlohmann/json

  1. 首先,确保你已经安装了 nlohmann/json 库。如果没有,请访问 https://github.com/nlohmann/json#integration 获取安装说明。

  2. 包含 json.hpp 头文件:

#include<iostream>
#include <fstream>
#include<string>
#include "json.hpp"

using json = nlohmann::json;
using namespace std;
  1. 从文件或字符串中读取 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);
  1. 访问 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;
}
  1. 修改 JSON 数据的值:
j["name"] = "Jane";
j["age"] = 25;
  1. 将 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 的文件。

0