-
-
Notifications
You must be signed in to change notification settings - Fork 6.8k
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
insert(or merge) object should replace same key , not ignore #661
Comments
This method should behave equivalent to
|
It was a pity that we limited by std::map::insert does not overwrite the exist key. So what is the problem with the operator [] ?example as void merge(json &j1, const json &j2) {
for (json::const_iterator it = j2.begin(); it != j2.end(); ++it) {
j1[it.key()] = it.value();
}
} |
Interestingly, there will be a
|
From Python 3.6, we could borrow the ideas from
So this would basically be your code with a different interface: void merge(const_reference j)
{
if (not (is_object() and j.is_object()))
{
JSON_THROW(type_error::create(305, "cannot use merge with " + type_name()));
}
for (auto it = j.begin(); it != j.end(); ++it) {
m_value.object->operator[](it.key()) = it.value();
}
} Any thoughts on this? |
std::map::insert_or_assign basically does this, although it does not operate on a range, just one element. I would say that is the most discoverable name. |
I think @nlohmann 's suggestion ok for now, The interface name can be either merge or insert_or_assign,but the function implementation no need to use c++ 17's std::map::insert_or_assign,until c++ 17 becomes a formal standard and is supported by mainstream compilers. |
Yes, I would not use the C++17 function until this library is C++17 only. It's very easy to implement the functionality. My suggestion was just about the naming. |
I would implement I tend to add the What about going the Python way and use |
It's an acceptable solution |
Via Twitter, I got further proposals:
|
|
Added a function |
As key "one" has exist, now the result j1 is still {{"one", 123}, {"two", 123}}
while I think more commonly used logic is replace the same key,that is the result should be {{"one", 456}, {"two", 123}}
Thanks
The text was updated successfully, but these errors were encountered: