2

I am using the json parser Json for Modern C++ (https://github.com/nlohmann/json). I know that I can get the value of a JSON value with a JSON_Pointer:

auto v1 = j["/a/b/c"_json_pointer];

But how would I go about getting the value if the JSON Pointer is defined at runtime (passed into my function)?

std:string s1 = "/a/b/c";
auto v1 = j[s1]; // doesn't work

You can't append "json_pointer" to either the std::string assignment or to the s1 variable. Is there a function that will convert a std::string to a json_pointer? The caller knows nothing about json and can't have access to the "json.hpp" header. I've also tried

std::string s1 = "/a/b/c";
json_pointer p1(s1);

but "json_pointer" class is undefined. Other than this issue this is a great library that does everything else I need. TIA.

Liviu
  • 1,859
  • 2
  • 22
  • 48
Ronald Currier
  • 575
  • 1
  • 5
  • 11

1 Answers1

7

Look at the source code:

inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t)
{
    return nlohmann::json::json_pointer(s);
}

If json_pointer is undefined, then you aren't using the right namespaces. Try

using nlohmann::json::json_pointer;
std::string s1 = "/a/b/c";
json_pointer p1(s1);
Taywee
  • 1,313
  • 11
  • 17
  • I swear that was the first thing I tried and wouldn't compile. Just tried again and it worked like a charm. Thanks for the quick and non-judgemental response. – Ronald Currier Jun 27 '16 at 23:29
  • 2
    No problem. Next time try to build a [MCVE](https://stackoverflow.com/help/mcve). Half the time when I'm running into an issue, I solve it just by building one in the first place. – Taywee Jun 27 '16 at 23:42