Json文件的解析

json文件以键值对形式记录信息,因提供了第三方接口函数便于文件信息而广泛作为配置文件使用。

一、linux系统下的安装

可通过指令直接安装:

sudo apt-get install libjsoncpp-dev

 二、Json文件的解析

1、解析键值对信息并保存所有键值对信息到一个map容器

void ReadJsonFile(const std::string& json_file1) {
  Json::Reader reader;
  Json::Value root;
  std::map<string, string> map_infor;
  std::cout << "read: " << json_file1 << endl;
  ifstream in_json1(json_file1, ios::binary);
  if (!in_json1.is_open()) {
    std::cout << "Error opening json file" << endl;
    exit(0);
  }
  std::cout << "start parse json file" << endl;
  if (reader.parse(in_json1, root)) {
    Json::Value::Members members = root.getMemberNames();
    for (auto& json_key_1 : members) {
      map_infor.emplace(json_key_1, root[json_key_1].asString());
    }
  } else {
    std::cout << "Parse json file error" << endl;
    exit(0);  // 解析文件失败退出
  }
  in_json1.close();
  return;
}

2、直接提取数据信息

void ReadJsonFile(const std::string& json_file2) {
  Json::Reader reader;
  Json::Value root;
  string id_1;
  string id_2;
  std::cout << "Read json file: " << json_file2 << endl;
  ifstream in_json2(json_file2, ios::binary);
  if (reader.parse(in_json2, root)) {
    id_1 = root["id_1"].asString();
    id_2 = root["id_2"].asString();
  }
  else {
    std::cout << "Parse json file error" << endl;
    exit(0);
  }
  in_json2.close();
  return;
}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值