如何在C++中解析jason數(shù)據(jù)

c++
小樊
82
2024-09-14 10:24:55

在 C++ 中解析 JSON 數(shù)據(jù),你可以使用第三方庫(kù),例如 nlohmann/json

  1. 首先,確保你已經(jīng)安裝了 nlohmann/json 庫(kù)。如果沒(méi)有,請(qǐng)?jiān)L問(wèn) https://github.com/nlohmann/json#integration 獲取安裝說(shuō)明。

  2. 包含 json.hpp 頭文件:

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

using json = nlohmann::json;
using namespace std;
  1. 從文件或字符串中讀取 JSON 數(shù)據(jù):
// 從文件讀取 JSON 數(shù)據(jù)
ifstream ifs("example.json");
json j = json::parse(ifs);

// 從字符串讀取 JSON 數(shù)據(jù)
string json_str = R"({"name": "John", "age": 30, "city": "New York"})";
json j = json::parse(json_str);
  1. 訪問(wèn) JSON 數(shù)據(jù)的值:
// 獲取 JSON 對(duì)象的鍵值對(duì)
string name = j["name"];
int age = j["age"];
string city = j["city"];

// 獲取 JSON 數(shù)組的元素
json arr = j["array"];
for (const auto& elem : arr) {
    cout<< elem<< endl;
}
  1. 修改 JSON 數(shù)據(jù)的值:
j["name"] = "Jane";
j["age"] = 25;
  1. 將 JSON 數(shù)據(jù)寫(xiě)入文件或字符串:
// 將 JSON 數(shù)據(jù)寫(xiě)入文件
ofstream ofs("output.json");
ofs << j;

// 將 JSON 數(shù)據(jù)轉(zhuǎn)換為字符串
string json_str = j.dump();

這是一個(gè)完整的示例代碼:

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

using json = nlohmann::json;
using namespace std;

int main() {
    // 從文件讀取 JSON 數(shù)據(jù)
    ifstream ifs("example.json");
    json j = json::parse(ifs);

    // 訪問(wèn) JSON 數(shù)據(jù)的值
    string name = j["name"];
    int age = j["age"];
    string city = j["city"];

    // 修改 JSON 數(shù)據(jù)的值
    j["name"] = "Jane";
    j["age"] = 25;

    // 將 JSON 數(shù)據(jù)寫(xiě)入文件
    ofstream ofs("output.json");
    ofs << j;

    return 0;
}

在這個(gè)示例中,我們從名為 example.json 的文件中讀取 JSON 數(shù)據(jù),訪問(wèn)其中的值,修改它們,然后將修改后的 JSON 數(shù)據(jù)寫(xiě)入名為 output.json 的文件。

0