You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hi,
when dealing with external json-data, it is not certain that a given key exists.
I frequently have constructs like these: if (json.contains("key") && json["key"] == expected_value) { ... }
This looks up "key" twice and repeats "key" as a potential copy&paste-error.
I therefore propose to add a simple contains-overload to basic_json:
template<typename T, class KeyType, detail::enable_if_t<
detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
bool contains(KeyType && key, const T& compare_value) const
{
auto it = find(std::forward<KeyType>(key));
if (it != end())
return it->template get<T>() == compare_value;
return false;
}
Of course this should be [[nodiscard]], however adhering to the lib-style, I left it as it is.
Overall, I think this overload is
useful syntactic sugar
its naming is intuitive enough
it improves code-quality
reduces potential errors.
I understand that this situation can be solved by using value<T>(Key, default_value) == expected_value, however since this constructs the default_value just to compare it, may be less efficient. It also is error-prone in the sense that default_value must be chosen to not be expected_value.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Hi,
when dealing with external json-data, it is not certain that a given key exists.
I frequently have constructs like these:
if (json.contains("key") && json["key"] == expected_value) { ... }
This looks up "key" twice and repeats "key" as a potential copy&paste-error.
I therefore propose to add a simple contains-overload to basic_json:
Of course this should be [[nodiscard]], however adhering to the lib-style, I left it as it is.
Overall, I think this overload is
I understand that this situation can be solved by using
value<T>(Key, default_value) == expected_value
, however since this constructs the default_value just to compare it, may be less efficient. It also is error-prone in the sense that default_value must be chosen to not be expected_value.Beta Was this translation helpful? Give feedback.
All reactions