C++でJSONを扱いたいとき、以前は picojson を使っていた。
近ごろは nlohmann-json が良いらしい。(しらんけど)
(ファイルサイズはpicojsonのほうが圧倒的に小さい。というか、nlohmann-jsonはクソデカい。)
ヘッダオンリー
- picojson もそうだが、nlohmann-json もヘッダファイルだけで (も) 利用できる。
- ライブラリをインストールすることも可能。
- Ubuntuの場合、「sudo apt install nlohmann-json3-dev」
- ヘッダのみで利用する場合は、下記のファイルをダウンロードして使用する。
json/single_include/nlohmann/json.hpp at develop · nlohmann/json · GitHub
インクルード
#include <nlohmann/json.hpp> // インストールした場合
#include "json.hpp" // ヘッダオンリーの場合 (ディレクトリは適宜)
JSONファイルを読み込む
#include <iostream> #include <fstream> #include <nlohmann/json.hpp> using json = nlohmann::json; ... std::string json_path= "input.json"; std::ifstream file(json_path); if (!file.is_open()) { // エラー処理 } json j; file >> j;
JSONファイルに書き出す
std::string json_path= "output.json"; std::ofstream file(json_path); if (!file.is_open()) { // エラー処理 } file << j.dump(4); // インデントを4に設定して書き出し file.close();
標準出力にダンプ
std::cout << j.dump(4) << std::endl;
初期化リスト
json j = { {"hoge", 123}, {"piyo", "piyopiyo"} };
値の設定
int hoge = 123; std::string piyo = "piyopiyo"; j["hoge"] = hoge; j["piyo"] = piyo;
値の取得
int hoge; std::string piyo; try { hoge = j["hoge"].get<int>(); piyo = j["piyo"].get<std::string>(); } catch (json::exception& e) { // エラー処理 }