jsoncpp icon indicating copy to clipboard operation
jsoncpp copied to clipboard

how to check if the key existed in Json::Value?

Open bethebest0622 opened this issue 3 years ago • 4 comments

I have a Json::Value object.

I want to check if there is a key = 'data'.

Is there any method can do this? i think find method is not the correct method

bethebest0622 avatar Jul 03 '22 15:07 bethebest0622

You said no, but I really think find is what you need.

BillyDonahue avatar Jul 04 '22 02:07 BillyDonahue

could you provide a demo of find?

I am confused why find need two parameters, usually, find should only contains one parameter.

bethebest0622 avatar Jul 04 '22 03:07 bethebest0622

find takes one string, but it's in the form of a {begin,end} range of char pointers. This done so that it doesn't constrain the users to one particular string type.

In C++17 parlance it would be a passed as a single std::string_view.

std::string k = "theKey";
auto iter = value.find(k.begin(), k.end());
if (iter == k.end())
    ... // no such key
else {
    iter->first is a key
    iter->second is a Value
}

BillyDonahue avatar Jul 04 '22 04:07 BillyDonahue

There are also overloads:

bool isMember(const char* key) const;
bool isMember(const String& key) const;
bool isMember(const char* begin, const char* end) const;

Where String should be compatible with std::string:

using String = std::basic_string<char, std::char_traits<char>, Allocator<char>>;

Also worth checking for first, otherwise it throws exception if it is not:

 bool isObject() const;

antoshkaplus avatar May 29 '24 18:05 antoshkaplus