ものづくりのブログ

うちのネコを題材にしたものづくりができたらいいなと思っていろいろ奮闘してます。

【c++】json の扱い方

c++ で jsonを扱う方法を調べてみたのでここにメモします。

今回は nlohmann より公開されているライブラリを使用しました。

github.com

「single_include/nlohmann/」配下の”json.hpp”を作成しているソースコードと同階層に格納すればライブラリが使用できます。

サンプル

コード

#include <iostream>
#include "json.hpp"

int main()
{
    using json = nlohmann::json;

    std::string jsonstr = R"({"str":"おはよう。","boolian":false,"person":[{"name":"Sato","age":20},{"name":"Kato","age":30}]})";

    auto jobj = json::parse(jsonstr);
    std::cout << jobj << std::endl;
}

コンパイル

$ g++ -o test test.cpp 

実行結果

$ ./test | jq
{
  "boolian": false,
  "person": [
    {
      "age": 20,
      "name": "Sato"
    },
    {
      "age": 30,
      "name": "Kato"
    }
  ],
  "str": "おはよう。"
}