溫馨提示×

c++怎么讀取json文件內容

小億
260
2024-01-25 11:59:33
欄目: 編程語言

要讀取JSON文件內容,可以使用C++中的第三方庫,如RapidJSON或nlohmann/json。以下是使用RapidJSON庫的示例代碼:

```cpp

#include

#include

#include

#include "rapidjson/document.h"

int main() {

std::ifstream file("example.json");

std::string jsonData((std::istreambuf_iterator(file)), std::istreambuf_iterator());

rapidjson::Document doc;

doc.Parse(jsonData.c_str());

if (doc.HasParseError()) {

std::cout << "Failed to parse JSON file." << std::endl;

return 1;

}

// 在這里可以根據需要訪問、操作JSON文件中的數據

return 0;

}

```

請注意,您需要先安裝RapidJSON庫,并在代碼中包含合適的頭文件。

另外,如果您使用的是nlohmann/json庫,代碼示例如下:

```cpp

#include

#include

#include

#include

int main() {

std::ifstream file("example.json");

nlohmann::json jsonData;

file >> jsonData;

// 在這里可以根據需要訪問、操作JSON文件中的數據

return 0;

}

```

同樣,您需要先安裝nlohmann/json庫,并在代碼中包含合適的頭文件。

以上示例代碼中,"example.json"為要讀取的JSON文件的路徑。讀取后,您可以使用RapidJSON或nlohmann/json庫提供的方法訪問、操作JSON文件中的數據。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女