kazuho / picojson

a header-file-only, JSON parser serializer in C++
BSD 2-Clause "Simplified" License
1.12k stars 221 forks source link

add bracket operator and opt #81

Closed satoren closed 8 years ago

satoren commented 8 years ago

Motivation. If the value does not exist, want to assign from default value, but it requires a error checking.

e.g. want get "sample" if "a.b" is a std::string. "default" otherwise.

{"a":{"b":"sample"}}

current vesion

  std::string result = "default";
  if(v.is<picojson::object>())
  {
    const picojson::value& a =  v.get("a");
    if(a.is<picojson::object>())
    {
      const picojson::value& b = a.get("b");
      result = b.is<std::string>()? b.get<std::string>():result;
    }
  }

with this PR.

std::string result = v["a"]["b"].opt(std::string("default"));

It's simple!