c++怎么读取json文件内容

627
2024/2/11 11:59:33
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要读取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文件中的数据。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c++中return 0的作用是什么