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
if the key is not found return a default_value of type T (possibly moved in and out)
if the key is found return the object converted to type T (only if T is compatible)
e.g.
template <typename T>
T at (const typename object_t::key_type & key, T default_value) const noexcept
{
auto it = find(key);
if (it != end()) return *it;
return default_value;
}
I don't think this is a good idea, because I would like the operator[] to "feel" like the one of std::map. And there, an exception is thrown if the container does not have an element with the specified key.
Ah, insert_or_assign is different than want @dariomt is asking. I'm just suggesting to add insert_or_assign, it's added to the container types in c++17. I think at() is good name for what @dariomt wants and similar to the STL. Maybe at_default() is better? boost::property_tree might give some inspiration: http://www.boost.org/doc/libs/1_59_0/doc/html/property_tree/accessing.html
The standard containers' at() function returns a reference to the member allowing modification. If our new function returns a copy instead (which it has to do in order to be able to return the default value) then I'd rather the function wasn't named at() in order to avoid ambiguity.
Qt's QList template class provides such a function called value() instead. It also provides an at() compatible with the standard library's at() thereby completely avoiding ambiguity. QList provides two variants of value(), one taking only a single index argument which returns a default-constructed instance in case of non-existence and an overload taking both an index and the default value to return. I rather like this flexibility.
About returning the default value instead of throwing: from the perspective of least surprise I'd argue that value() only makes sense for array and object types. Therefore it should not work for other types.
Note that it's also easier to disallow other types first and to change the API later if users request it to work on other types as well then the other way around: if you allow it now and decide to disallow it later it would break the API and therefore potentially existing applications.
As I mentioned in my original post, my use case is more in line with:
template <typename T>
T value(consttypenameobject_t::key_type& key, T default_value) const
because when I'm looking for a key I already know the type the associated value should have, and I expect that I can get the converted-to-T value if the key is found, or the default-T if it is not found.
My guess:
The return statement inside value() tries to convert from basic_json to T, but such conversion is not possible because basic_json is implicitly convertible to std::string but not to const char*. That's why the second case works, because in that case T is std::string.
My suggestion: add an overload to take care of that case, that creates a StringType for the default value and redirects to the main value().
// overload for a default value of type const char*
StringType value(consttypenameobject_t::key_type& key, constchar* default_value) const
{
returnvalue(key, StringType(default_value));
}
If you don't like my suggestion, then you could static_assert that basic_json is implicitly convertible to T inside value(), to give a user-friendly error message at compile time.
If using the template, you need to make it deduce a type that is implicitly convertible both to and from value_type. This means that either you provide the T explicitly as in j.valuestd::string("key", "default string"), or you make sure that the default value is that type, as in j.value("key", "default string"s). To put the error at the point of use, you could add enable_if as you do in the constructors.
Hi there, one more question: What do you think of a second version of value which always returns a basic_json value and implicitly return a null value as default?
I think this "with default" version would be much more useful now that [] can no longer be used on const objects. I did a local build of our code with the updated version, and had to do a lot of replacing of foo[key] with *foo.find(key), and would much prefer foo.value(key).
Another idea for the version without explicit default value: Instead of returning json() as default value, I could return *this. This would allow a version of value(key) that always returns const references.
After thinking about it for quite a while, removing the const version of operator[] was a mistake. I re-added it in a previous commit. I think now the value function does not need another version with implicit default value, right?
Activity
nlohmann commentedon Oct 11, 2015
I don't think this is a good idea, because I would like the
operator[]to "feel" like the one ofstd::map. And there, an exception is thrown if the container does not have an element with the specified key.dariomt commentedon Oct 13, 2015
OK, understood.
Would you consider adding this functionality with a different name?
rigtorp commentedon Nov 14, 2015
Something equivalent of this would be great. I don't know why the STL doesn't have this. In C++17 there is insert_or_assign(), but no equivalent to python's dict.get() https://docs.python.org/2/library/stdtypes.html#dict.get. JsonCpp have this too http://open-source-parsers.github.io/jsoncpp-docs/doxygen/class_json_1_1_value.html#a28282c9b76fa031eba7a1843c47c16fe
I don't know why the STL missed this common usecase.
nlohmann commentedon Nov 14, 2015
I'm on holiday right now. I'll have a look then.
nlohmann commentedon Dec 7, 2015
I think the
insert_or_assign()would be misleading, because as far as I understood @dariomt, the object shall be left unchanged.Any name proposals better than
at?rigtorp commentedon Dec 9, 2015
Ah, insert_or_assign is different than want @dariomt is asking. I'm just suggesting to add insert_or_assign, it's added to the container types in c++17. I think at() is good name for what @dariomt wants and similar to the STL. Maybe at_default() is better? boost::property_tree might give some inspiration: http://www.boost.org/doc/libs/1_59_0/doc/html/property_tree/accessing.html
dariomt commentedon Dec 9, 2015
maybe
at_or_default()?mbunkus commentedon Dec 9, 2015
The standard containers'
at()function returns a reference to the member allowing modification. If our new function returns a copy instead (which it has to do in order to be able to return the default value) then I'd rather the function wasn't namedat()in order to avoid ambiguity.Qt's
QListtemplate class provides such a function calledvalue()instead. It also provides anat()compatible with the standard library'sat()thereby completely avoiding ambiguity.QListprovides two variants ofvalue(), one taking only a single index argument which returns a default-constructed instance in case of non-existence and an overload taking both an index and the default value to return. I rather like this flexibility.nlohmann commentedon Dec 11, 2015
Good point with the reference! I guess
value()would be a good candidate. I see if I can fix something this weekend.nlohmann commentedon Dec 13, 2015
What do you think of the following:
It allows code like
int i = j.value("key_key", 17);orj.value("other_key")to usenullas default value.nlohmann commentedon Dec 14, 2015
I forgot: Of course, the above could could be
noexceptand also return the default value if called on a JSON value other than an object.mbunkus commentedon Dec 14, 2015
I like your proposed implementation.
About returning the default value instead of throwing: from the perspective of least surprise I'd argue that
value()only makes sense for array and object types. Therefore it should not work for other types.Note that it's also easier to disallow other types first and to change the API later if users request it to work on other types as well then the other way around: if you allow it now and decide to disallow it later it would break the API and therefore potentially existing applications.
dariomt commentedon Dec 14, 2015
As I mentioned in my original post, my use case is more in line with:
because when I'm looking for a key I already know the type the associated value should have, and I expect that I can get the converted-to-T value if the key is found, or the default-T if it is not found.
To me that's the meaning
value()conveys.nlohmann commentedon Dec 14, 2015
@dariomt
I tried, but with the template I fail to compile a call like
j.value("key", "default string"), because ofWhen I write
j.value("key", std::string("default string")), it works.Any idea?
dariomt commentedon Dec 14, 2015
My guess:
The return statement inside
value()tries to convert frombasic_jsontoT, but such conversion is not possible becausebasic_jsonis implicitly convertible tostd::stringbut not toconst char*. That's why the second case works, because in that caseTisstd::string.My suggestion: add an overload to take care of that case, that creates a
StringTypefor the default value and redirects to the mainvalue().If you don't like my suggestion, then you could
static_assertthatbasic_jsonis implicitly convertible toTinsidevalue(), to give a user-friendly error message at compile time.gregmarr commentedon Dec 14, 2015
If using the template, you need to make it deduce a type that is implicitly convertible both to and from value_type. This means that either you provide the T explicitly as in j.valuestd::string("key", "default string"), or you make sure that the default value is that type, as in j.value("key", "default string"s). To put the error at the point of use, you could add enable_if as you do in the constructors.
fix for #133
nlohmann commentedon Dec 15, 2015
I added the function with some documentation and example: http://nlohmann.github.io/json/classnlohmann_1_1basic__json_a26b7e4876af25eae5800ce43f93aaef2.html#a26b7e4876af25eae5800ce43f93aaef2
nlohmann commentedon Dec 16, 2015
Hi there, one more question: What do you think of a second version of
valuewhich always returns abasic_jsonvalue and implicitly return a null value as default?gregmarr commentedon Dec 17, 2015
I think this "with default" version would be much more useful now that [] can no longer be used on const objects. I did a local build of our code with the updated version, and had to do a lot of replacing of foo[key] with *foo.find(key), and would much prefer foo.value(key).
nlohmann commentedon Dec 17, 2015
Ok, will so.
nlohmann commentedon Dec 19, 2015
Another idea for the version without explicit default value: Instead of returning
json()as default value, I could return*this. This would allow a version ofvalue(key)that always returns const references.nlohmann commentedon Dec 21, 2015
After thinking about it for quite a while, removing the const version of
operator[]was a mistake. I re-added it in a previous commit. I think now thevaluefunction does not need another version with implicit default value, right?