nlohmann::jsonの使用例を殆どやっていなかったことに気づいたのでここに置いておく。
#include <iostream> #include <nlohmann/json.hpp> #include <fstream> int main() { // json形式の文字列 std::string jsontext = R"( { "information":{ "Name":"Tarou", "Age":18, "weight":60.5 }, "data":{ "dates":[ "2023-10-01T12:00:00+09:00", "2023-10-02T12:00:00+09:00" ], "countries":[ { "id":1, "name":"Russia" }, { "id":2, "name":"France" } ] } } )"; //std::string filename = R"(C:\test\data\data.json)"; //std::ifstream file(filename); //nlohmann::json jsondata = nlohmann::json::parse(file); nlohmann::json jsondata = nlohmann::json::parse(jsontext); { nlohmann::json information = jsondata["information"]; // データの取得 std::string name = information["Name"]; int age = information["Age"]; double weight = information["weight"]; std::cout << "Name: " << name << std::endl; std::cout << "Age: " << age << std::endl; std::cout << "Weight: " << weight << std::endl; } { nlohmann::json data = jsondata["data"]; { nlohmann::json dates = data["dates"]; for (const auto& date : dates) { std::string date_str = date.get<std::string>(); std::cout << "Date: " << date_str << std::endl; } } { nlohmann::json countries = data["countries"]; for (const auto& country : countries) { int id = country["id"]; std::string name = country["name"]; std::cout << "Country ID: " << id << ", Name: " << name << std::endl; } } } }
構造体で受け取ることもできるが、あらかじめfrom_json関数を定義しておく必要がある
struct Country { int id; std::string name; };
// .get関数を使用するための定義 void from_json(const nlohmann::json& j, Country& p) { j.at("id").get_to(p.id); j.at("name").get_to(p.name); }
int main() { std::string filename = R"(C:\test\data\data.json)"; std::ifstream file(filename); nlohmann::json jsondata = nlohmann::json::parse(file); nlohmann::json data = jsondata["data"]; { std::vector<std::string> vectors = data["dates"]; for (const auto& date : vectors) { std::cout << "Date from vector: " << date << std::endl; } } { std::vector<Country> countries = data["countries"].get<std::vector<Country> >(); for (const auto& country : countries) { std::cout << "Country ID: " << country.id << ", Name: " << country.name << std::endl; } } }