boostorg / boostorg/json

Support for ordered insert/erase on json::object

Open
#748 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
479
Forks
110
Avg merge
10d 3h
Merged PRs (30d)
5

Description

I have a json that needs to be manipulated and maintaining the order of the keys in the object is really imported (even though it is supposed to be unordered key-value map).

Currently insertions are ordered so creating a json::object and inserting at the end will preserve the order. A work around I have now is something like this:
```c++
template
void ordered_insert_before(boost::json::object& o, K&& key, P&& p)
{
auto x = boost::json::object(o.storage());
x.reserve(o.size() + 1);
bool added = false;
for (auto&& [k, v] : o)
{
if (k == key && !added)
{
x.insert(std::forward

(p));
added = true;
}
x.insert(boost::json::object::value_type{std::move(k), std::move(v)});
}
if (!added)
{
x.insert(std::forward

(p));
}
o.swap(x);
}

template
void ordered_erase(boost::json::object& o, K&& key)
{
auto x = boost::json::object(o.storage());
x.reserve(o.size());
for (auto&& [k, v] : o)
{
if (k != key)
{
x.insert(boost::json::object::value_type{std::move(k), std::move(v)});
}
}
o.swap(x);
}
```

There are of course O(N). Is there interest for adding these as member functions or free functions with stronger ordering guarantees but worse O(N) complexity + allocations?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.