C++とダイナミックなJson

概要

C++にて構造が複雑だったり不定形なjsonを扱うの出れば、nlohmann/json が有名で、
非常に便利に使えます。

C++とダイナミックなJson

  • C++側のソース

    Jsonの非常に柔軟な取り扱い
    #include "json.hpp"
    
    using json = nlohmann::json;
    
    // create an empty structure (null)
    json j;
    
    // add a number that is stored as double (note the implicit conversion of j to an object)
    j["pi"] = 3.141;
    
    // add a Boolean that is stored as bool
    j["happy"] = true;
    
    // add a string that is stored as std::string
    j["name"] = "Niels";
    
    // add another null object by passing nullptr
    j["nothing"] = nullptr;
    
    // add an object inside the object
    j["answer"]["everything"] = 42;
    
    // add an array that is stored as std::vector (using an initializer list)
    j["list"] = { 1, 0, 2 };
    
    // add another object (using an initializer list of pairs)
    j["object"] = { {"currency", "USD"}, {"value", 42.99} };
    
    // instead, you could also write (which looks very similar to the JSON above)
    json j2 = {
      {"pi", 3.141},
      {"happy", true},
      {"name", "Niels"},
      {"nothing", nullptr},
      {"answer", {
        {"everything", 42}
      }},
      {"list", {1, 0, 2}},
      {"object", {
        {"currency", "USD"},
        {"value", 42.99}
      }}
    };
    
    // parse explicitly
    auto j3 = json::parse(R"({"happy": true, "pi": 3.141})");
    
    // a JSON value
    json j_original = R"({
      "baz": ["one", "two", "three"],
      "foo": "bar"
    })"_json;
    
    // access members with a JSON pointer (RFC 6901)
    j_original["/baz/1"_json_pointer];
    // "two"
    
    // a JSON patch (RFC 6902)
    json j_patch = R"([
      { "op": "replace", "path": "/baz", "value": "boo" },
      { "op": "add", "path": "/hello", "value": ["world"] },
      { "op": "remove", "path": "/foo"}
    ])"_json;
    
    // apply the patch
    json j_result = j_original.patch(j_patch);
    // {
    //    "baz": "boo",
    //    "hello": ["world"]
    // }
    
    // calculate a JSON patch from two JSON values
    json::diff(j_result, j_original);
    // [
    //   { "op":" replace", "path": "/baz", "value": ["one", "two", "three"] },
    //   { "op": "remove","path": "/hello" },
    //   { "op": "add", "path": "/foo", "value": "bar" }
    // ]