-
-
Notifications
You must be signed in to change notification settings - Fork 6.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
is it possible to check existence of a value deep in hierarchy? #584
Comments
No, this is currently not possible without exceptions. |
thank you |
You may try the following: auto j_flatten = json::flatten(j);
if (j_flatten.find("/this/that/then") != j_flatten.end())
... I think |
No, this is way too expensive (and it also throws, just in different circumstances (out of memory). |
I see. Then I fear you have to be patient until we add more support for situations where exceptions are switched off. May I ask in which situation you are using the library? |
cmdline app that receives a 'job definition' json, checks few values at various places in the tree (tweaks few things, if need be) and submits it for execution to another portion of code (aka engine). Btw, few notes:
you could make it even faster if you assume that next field is likely to follow previously found one and provide hint to subsequent lookup. Basically, if user's json has same layout as related struct in memory -- there will be no search at all.
Is there a better way? Or maybe in case 2 it is guaranteed that default value is passed by reference and operator[] is inline? |
Here is a snippet using C++11 or later: Example: nlohnmann::json obj = nlohmann::parse("{'foo': 'bar': {'baz': 100}}");
nlohnmann::json deep = Util::resolve(obj, {"music", "ytcracker", "baz"}); nlohmann::json Util::resolve(nlohmann::json obj, std::initializer_list<std::string> keys) {
nlohmann::json j = obj;
for (auto& key : keys) {
if (!j.is_object()) {
return nlohmann::json();
}
auto exists = j.find(key);
if (exists == j.end()) {
return nlohmann::json();
}
j = *exists;
}
return j;
} |
Smth like this:
I can use
j.value(ptr, def_value)
, but then I can't tell if node actually existed. I can usej.at(...)
-- but I don't want to deal with exceptions.Edit:
j.value()
approach doesn't seem to work either...The text was updated successfully, but these errors were encountered: