温馨提示×

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

小亿
104
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