0
点赞
收藏
分享

微信扫一扫

[C++][原创]nlohman的json简单使用


nlohmann/json 是一个用于解析json的开源c++库,使用方便直观。
nlohmann库
nlohmann库(https://github.com/nlohmann/json)提供了丰富而且符合直觉的接口(https://json.nlohmann.me/api/basic_json/),只需导入头文件即可使用,方便整合到项目中。
 

#include <iostream>
#include <fstream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using namespace std;
int main(int argc, char *argv[])
{
  std::string json_data = "{\"name\":\"Alice\",\"age\":18,\"weight\":120.1}";
  json data_dict = json::parse(json_data);
  std::string name = data_dict["name"];            // 获取字符串值,方法1
  std::string name1 = data_dict.at("name");        // 获取字符串值,方法2
  int age = data_dict["age"].get<int>();           // 获取Int值
  float weight = data_dict["weight"].get<float>(); // 获取float值
  std::string data = data_dict.dump();             // json转字符串

  if (data_dict.contains("name")) // 判断是否存在某个键
  {
    std::cout << "name in key!\n";
  }

  if (!data_dict.contains("cloth")) // 判断是否存在某个键
  {
    std::cout << "cloth not in key!\n";
  }

 //循环遍历键值对
  for (auto& x : data_dict.items())
    {
        std::cout << "key: " << x.key() << ", value: " << x.value() << '\n';
    }
  std::cout << data << std::endl;
  return 0;
}

举报

相关推荐

0 条评论