用jsoncpp提取json文件中的部分键值对并存到另一个变量
时间: 2024-04-30 09:21:38 浏览: 195
假设我们有一个名为 `config.json` 的 JSON 文件,其中包含以下内容:
```json
{
"name": "John",
"age": 30,
"city": "New York",
"job": "Engineer"
}
```
现在我们想要提取其中的 `name` 和 `job` 键值对,并将它们存储到另外两个变量中。
可以使用 jsoncpp 库来解析 JSON 文件。首先需要包含 jsoncpp 的头文件:
```c++
#include <jsoncpp/json/json.h>
```
然后,我们可以使用 `Json::Value` 类型来表示 JSON 数据,并使用 `Json::Reader` 类型来解析 JSON 文件。以下是一个示例代码:
```c++
#include <iostream>
#include <fstream>
#include <jsoncpp/json/json.h>
using namespace std;
int main() {
// 读取 JSON 文件
ifstream file("config.json");
Json::Value root;
Json::Reader reader;
bool success = reader.parse(file, root);
if (!success) {
cerr << "Failed to parse JSON file" << endl;
return 1;
}
// 从 JSON 对象中提取 name 和 job 键值对
string name = root["name"].asString();
string job = root["job"].asString();
// 输出结果
cout << "Name: " << name << endl;
cout << "Job: " << job << endl;
return 0;
}
```
执行上述代码,将会输出以下结果:
```
Name: John
Job: Engineer
```
以上代码中,`root["name"]` 和 `root["job"]` 分别表示从 JSON 对象 `root` 中提取 `name` 和 `job` 键值对的值。这些值可以通过 `asString()` 方法转换为字符串类型,并存储到相应的变量中。
阅读全文
相关推荐
















