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
{{ message }}
Repository navigation
Object properties should not be re-sorted alphabetically #2179
Sure though the commented output under std::unordered_map above is misguiding. I suggest correcting it to highlight the actual order.
To preserve insertion order in my use case, I made a minimal solution based on std::vector.
Leaving it here for those who for any reason don't want to import further non-standard dependencies, or want a starting point to build their own:
/// VecMap: a minimal map-like container that preserves insertion order
/// for use within nlohmann::basic_json<VecMap>
template<class Key, class T, class IgnoredLess=std::less<Key>,
class Allocator = std::allocator<std::pair<const Key, T>>,
class Container = std::vector<std::pair<const Key, T>, Allocator>>
struct VecMap : Container
{
using key_type = Key;
using mapped_type = T;
using value_type = std::pair<const Key, T>;
using Container::Container;
auto emplace( Key && key, T && t ) {
for (auto it=this->begin(); it !=this->end(); ++it)
if (it->first == key)
return std::pair {it, false};
this->emplace_back(key, t);
return std::pair {--this->end(), true};
}
T& operator[]( Key && key ) {
return emplace(std::move(key), T{}).first->second;
}
};
It works well in my tests.
It is an effective choice for small objects due to the low overhead of std::vector. And its algorithmic simplicity makes it a good target for compiler optimization.
using Json = nlohmann::json;
using FifoJson = nlohmann::basic_json<VecMap>;
vector<pair<string,string>> vec {{"Z","1"},{"Y","2"},{"X","3"}};
cout << Json(vec) << endl;
// => [["Z","1"],["Y","2"],["X","3"]] - array, not object
VecMap<string,string> vm {{"Z","1"}};
vm["Z"] = "2";
vm["Y"] = "3";
vm["X"] = "4";
cout << Json(vm) << endl; // VecMap::mapped_type makes it look like a map ~ object
// => {"X":"4","Y":"3","Z":"2"}
cout << FifoJson(vm) << endl;
// => {"Z":"2","Y":"3","X":"4"} - Object, in insertion order
FifoJson fj {{"Z","1"},{"Y","2"},{"X",3}};
fj["Z"] = 4;
fj["A"] = 5;
cout << fj << endl;
// => {"Z":4,"Y":"2","X":3,"A":5}
I am currently trying to put this all together to add this as ordered_json to the library. While writing tests, I saw that removing elements is not yet working. This is my current approach:
std::size_terase(const key_type& key)
{
std::size_t result = 0;
for (auto it = this->begin(); it != this->end();)
{
if (it->first == key)
{
++result;
it = Container::erase(it);
}
else
{
++it;
}
}
return result;
}
which fails due to an error in it = Container::erase(it);:
cannot be assigned because its copy assignment operator is implicitly deleted
Optimal: find if C++11 has some way to put AllocatorType<Container::value_type> inside the declaration of object_t. Note that Container::value_type == object_t::value_type == basic_json::value_type so it is a self-referencing template... Seems beyond my template abilities, but it would clear the way to any Container class, not just std::vector.
Probably the cleanest way is by wrapping std::map:
template<class Key, class T, template<class> AllocatorType>
class MapWrapper : std:map<Key, T, std::less<Key>, AllocatorType<const Key, T>> {}
then ObjectType = MapWrapper, and object_t declaration would be much simpler:
Only I would not want to go into mayor refactoring 🙂 so...
Re-implement vector::erase() without relying on pair move operations missing due to const member. e.g. by using in-place destructor + constructor. I am working at this now.
Use std::forward_list instead of std::vector. Me not like it, but should work.
@nlohmann I think this should have been named unordered_json, in-line with what std::map, std::unordered_map, std::set, std::unordered_set do.
std::map orders its elements in a particular fashion, while std::unordered_map preserves the order in which its elements are inserted. So std::map is actually an alias for ordered_map
Similarly nhlomann::json should have been alias for ordered_json as implicitly sorts the elements and nhlomann::unordered_json should preserve the order of insertion (i.e. it does not sort). 😄
std::map orders its elements in a particular fashion, while std::unordered_map preserves the order in which its elements are inserted.
This is not true. In std::unordered_map, elements are hashed and stored in buckets.
Similarly nhlomann::json should have been alias for ordered_json as implicitly sorts the elements and nhlomann::unordered_json should preserve the order of insertion (i.e. it does not sort). 😄
Activity
nlohmann commentedon Jun 8, 2020
This behavior is described in the readme including ways to circumvent it.
gatopeich commentedon Jun 8, 2020
Thanks, I had missed the Order of object keys section in README.
Great library BTW.
gatopeich commentedon Jun 8, 2020
I just want to highlight that some
unordered_mapexample in the README does not seem to work:This produces exactly the same as the default:
nlohmann commentedon Jun 8, 2020
The README does not mention using
std::unordered_mapas workaround, buttsl::unordered_mapornlohmann::fifo_map, see https://github.com/nlohmann/json/blob/develop/README.md#order-of-object-keys.gatopeich commentedon Jun 10, 2020
Sure though the commented output under
std::unordered_mapabove is misguiding. I suggest correcting it to highlight the actual order.To preserve insertion order in my use case, I made a minimal solution based on
std::vector.Leaving it here for those who for any reason don't want to import further non-standard dependencies, or want a starting point to build their own:
Again, thanks for this great JSON library!
nlohmann commentedon Jun 10, 2020
Your
VecMapcontainer is very nice and compact. Can I use this as example in the documentation?gatopeich commentedon Jun 10, 2020
Of course 👍
gatopeich commentedon Jun 10, 2020
It works well in my tests.
It is an effective choice for small objects due to the low overhead of
std::vector. And its algorithmic simplicity makes it a good target for compiler optimization.gatopeich commentedon Jun 10, 2020
It was missing
using mapped_type = Tto be fully recognized. Just added it and updated the above comments...nlohmann commentedon Jun 19, 2020
@gatopeich
I am currently trying to put this all together to add this as
ordered_jsonto the library. While writing tests, I saw that removing elements is not yet working. This is my current approach:which fails due to an error in
it = Container::erase(it);:Any ideas? Here is the current state: 4fd0d02
16 remaining items
gatopeich commentedon Jun 21, 2020
The problem is in the definition of
object_tthere is an assumption that the allocator is for aconst string:And a
const stringmay have a specialized implementation, e.g. with smaller allocation requirements, thus with incompatible allocator...nlohmann commentedon Jun 22, 2020
I took the default template arguments from
std::map:I'm afraid changing this would break the API. Any idea how to fix the "vector of pairs" approach? Maybe using two vectors?
gatopeich commentedon Jun 22, 2020
I see 3 ways forward:
AllocatorType<Container::value_type>inside the declaration ofobject_t. Note thatContainer::value_type==object_t::value_type==basic_json::value_typeso it is a self-referencing template... Seems beyond my template abilities, but it would clear the way to any Container class, not just std::vector.Probably the cleanest way is by wrapping std::map:
then ObjectType = MapWrapper, and
object_tdeclaration would be much simpler:Only I would not want to go into mayor refactoring 🙂 so...
Re-implement
vector::erase() without relying on pair move operationsmissing due to const member. e.g. by using in-place destructor + constructor. I am working at this now.Use
std::forward_listinstead ofstd::vector. Me not like it, but should work.gatopeich commentedon Jul 6, 2020
Hey @nlohmann my pull request #2206 is ready and waiting...
gatopeich commentedon Jul 17, 2020
Thanks for taking this in!
shdxiang commentedon Dec 11, 2020
great feature @gatopeich
pkbehera commentedon Oct 27, 2022
@nlohmann I think this should have been named
unordered_json, in-line with whatstd::map,std::unordered_map,std::set,std::unordered_setdo.std::maporders its elements in a particular fashion, whilestd::unordered_mappreserves the order in which its elements are inserted. Sostd::mapis actually an alias forordered_mapSimilarly
nhlomann::jsonshould have been alias forordered_jsonas implicitly sorts the elements andnhlomann::unordered_jsonshould preserve the order of insertion (i.e. it does not sort). 😄nlohmann commentedon Oct 27, 2022
This is not true. In
std::unordered_map, elements are hashed and stored in buckets.See https://json.nlohmann.me/features/object_order/ on the rationale.