Skip to content
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

Add ordered_json specialization with ordered object keys #2258

Merged
merged 27 commits into from
Jul 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
4fd0d02
:construction: toward an ordered_json type
nlohmann Jun 19, 2020
6ee9e5f
:alembic: remove const from value type
nlohmann Jun 20, 2020
27aaf6f
Clean-up ordered_map declarations
Jun 21, 2020
15337b2
Ignore allocator hardcoded to match std::map
Jun 21, 2020
ddf0a45
Use AllocatorType<ObjectType::value_type>,
Jun 22, 2020
064a9c9
Fix regression test
Jun 22, 2020
5fe3d39
Using ordered_json instead of fifo_map in test-regression
Jun 22, 2020
49623a7
Revert "Using ordered_json instead of fifo_map in test-regression"
Jun 23, 2020
acd748e
Use std::map default allocator as a placeholder
Jun 23, 2020
fb8c11f
Re-implement ordered_map::erase,
Jun 23, 2020
5e7bdf1
Roll-back to hard-coded object_t::value_type
Jun 23, 2020
d08fca2
Use const Key in ordered map
Jun 23, 2020
08963d6
Revert types.md
Jun 23, 2020
cf18ba2
Test initialization with dup keys
Jun 23, 2020
49f26a0
Have 4 template parameters for ordered_map
Jun 29, 2020
0fc261f
Make ordered_map compatible with GCC 5.5
ap-viavi Jul 2, 2020
9377046
Precisely 4 template arguments for the sake of clang 3.6 (?)
ap-viavi Jul 3, 2020
25f5d75
Fix compilation for xcode 9.x
ap-viavi Jul 3, 2020
803c16e
Clean-up unintended changes to whitespace
ap-viavi Jul 3, 2020
0eb7b0a
Update README.md per review comments
gatopeich Jul 9, 2020
f62b462
Removing comment about AllocatorType per review request
Jul 9, 2020
f9a1fec
Remove redundant comment
gatopeich Jul 10, 2020
47d154d
Remove redundant comment
gatopeich Jul 10, 2020
5f146cb
Merge pull request #2206 from gatopeich/issue2179
nlohmann Jul 11, 2020
9c21285
Merge branch 'develop' of https://github.com/nlohmann/json into issue…
nlohmann Jul 11, 2020
3a80823
:twisted_rightwards_arrows: merge develop branch and resolve conflicts
nlohmann Jul 11, 2020
738c83d
:green_heart: add test for ordered_map
nlohmann Jul 11, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1574,7 +1574,9 @@ However, you can pass set parameter `ignore_comments` to true in the `parse` fun

### Order of object keys

By default, the library does not preserve the **insertion order of object elements**. This is standards-compliant, as the [JSON standard](https://tools.ietf.org/html/rfc8259.html) defines objects as "an unordered collection of zero or more name/value pairs". If you do want to preserve the insertion order, you can specialize the object type with containers like [`tsl::ordered_map`](https://github.com/Tessil/ordered-map) ([integration](https://github.com/nlohmann/json/issues/546#issuecomment-304447518)) or [`nlohmann::fifo_map`](https://github.com/nlohmann/fifo_map) ([integration](https://github.com/nlohmann/json/issues/485#issuecomment-333652309)).
By default, the library does not preserve the **insertion order of object elements**. This is standards-compliant, as the [JSON standard](https://tools.ietf.org/html/rfc8259.html) defines objects as "an unordered collection of zero or more name/value pairs".

If you do want to preserve the insertion order, you can try the type [`nlohmann::ordered_json`](https://github.com/nlohmann/json/issues/2179). Alternatively, you can use a more sophisticated ordered map like [`tsl::ordered_map`](https://github.com/Tessil/ordered-map) ([integration](https://github.com/nlohmann/json/issues/546#issuecomment-304447518)) or [`nlohmann::fifo_map`](https://github.com/nlohmann/fifo_map) ([integration](https://github.com/nlohmann/json/issues/485#issuecomment-333652309)).

### Memory Release

Expand Down
1 change: 1 addition & 0 deletions include/nlohmann/json.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ SOFTWARE.
#include <nlohmann/detail/output/serializer.hpp>
#include <nlohmann/detail/value_t.hpp>
#include <nlohmann/json_fwd.hpp>
#include <nlohmann/ordered_map.hpp>

/*!
@brief namespace for Niels Lohmann
Expand Down
13 changes: 13 additions & 0 deletions include/nlohmann/json_fwd.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,19 @@ uses the standard template types.
@since version 1.0.0
*/
using json = basic_json<>;

template<class Key, class T, class IgnoredLess, class Allocator>
struct ordered_map;

/*!
@brief ordered JSON class

This type preserves the insertion order of object keys.

@since version 3.9.0
*/
using ordered_json = basic_json<nlohmann::ordered_map>;

} // namespace nlohmann

#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_
71 changes: 71 additions & 0 deletions include/nlohmann/ordered_map.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
#pragma once

#include <functional> // less
#include <memory> // allocator
#include <utility> // pair
#include <vector> // vector

namespace nlohmann
{

/// ordered_map: a minimal map-like container that preserves insertion order
/// for use within nlohmann::basic_json<ordered_map>
template <class Key, class T, class IgnoredLess = std::less<Key>,
class Allocator = std::allocator<std::pair<const Key, T>>>
struct ordered_map : std::vector<std::pair<const Key, T>, Allocator>
{
using key_type = Key;
using mapped_type = T;
using Container = std::vector<std::pair<const Key, T>, Allocator>;
using typename Container::iterator;
using typename Container::size_type;
using typename Container::value_type;

// Explicit constructors instead of `using Container::Container`
// otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4)
ordered_map(const Allocator& alloc = Allocator()) : Container{alloc} {}
template <class It>
ordered_map(It first, It last, const Allocator& alloc = Allocator())
: Container{first, last, alloc} {}
ordered_map(std::initializer_list<T> init, const Allocator& alloc = Allocator() )
: Container{init, alloc} {}

std::pair<iterator, bool> emplace(key_type&& key, T&& t)
{
for (auto it = this->begin(); it != this->end(); ++it)
{
if (it->first == key)
{
return {it, false};
}
}
Container::emplace_back(key, t);
return {--this->end(), true};
}

T& operator[](Key&& key)
{
return emplace(std::move(key), T{}).first->second;
}

size_type erase(const Key& key)
{
for (auto it = this->begin(); it != this->end(); ++it)
{
if (it->first == key)
{
// Since we cannot move const Keys, re-construct them in place
for (auto next = it; ++next != this->end(); ++it)
{
it->~value_type(); // Destroy but keep allocation
new (&*it) value_type{std::move(*next)};
}
Container::pop_back();
return 1;
}
}
return 0;
}
};

} // namespace nlohmann
90 changes: 88 additions & 2 deletions single_include/nlohmann/json.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2822,6 +2822,19 @@ uses the standard template types.
@since version 1.0.0
*/
using json = basic_json<>;

template<class Key, class T, class IgnoredLess, class Allocator>
struct ordered_map;

/*!
@brief ordered JSON class

This type preserves the insertion order of object keys.

@since version 3.9.0
*/
using ordered_json = basic_json<nlohmann::ordered_map>;

} // namespace nlohmann

#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_
Expand Down Expand Up @@ -16000,6 +16013,79 @@ class serializer

// #include <nlohmann/json_fwd.hpp>

// #include <nlohmann/ordered_map.hpp>


#include <functional> // less
#include <memory> // allocator
#include <utility> // pair
#include <vector> // vector

namespace nlohmann
{

/// ordered_map: a minimal map-like container that preserves insertion order
/// for use within nlohmann::basic_json<ordered_map>
template <class Key, class T, class IgnoredLess = std::less<Key>,
class Allocator = std::allocator<std::pair<const Key, T>>>
struct ordered_map : std::vector<std::pair<const Key, T>, Allocator>
{
using key_type = Key;
using mapped_type = T;
using Container = std::vector<std::pair<const Key, T>, Allocator>;
using typename Container::iterator;
using typename Container::size_type;
using typename Container::value_type;

// Explicit constructors instead of `using Container::Container`
// otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4)
ordered_map(const Allocator& alloc = Allocator()) : Container{alloc} {}
template <class It>
ordered_map(It first, It last, const Allocator& alloc = Allocator())
: Container{first, last, alloc} {}
ordered_map(std::initializer_list<T> init, const Allocator& alloc = Allocator() )
: Container{init, alloc} {}

std::pair<iterator, bool> emplace(key_type&& key, T&& t)
{
for (auto it = this->begin(); it != this->end(); ++it)
{
if (it->first == key)
{
return {it, false};
}
}
Container::emplace_back(key, t);
return {--this->end(), true};
}

T& operator[](Key&& key)
{
return emplace(std::move(key), T{}).first->second;
}

size_type erase(const Key& key)
{
for (auto it = this->begin(); it != this->end(); ++it)
{
if (it->first == key)
{
// Since we cannot move const Keys, re-construct them in place
for (auto next = it; ++next != this->end(); ++it)
{
it->~value_type(); // Destroy but keep allocation
new (&*it) value_type{std::move(*next)};
}
Container::pop_back();
return 1;
}
}
return 0;
}
};

} // namespace nlohmann


/*!
@brief namespace for Niels Lohmann
Expand Down Expand Up @@ -16126,7 +16212,7 @@ class basic_json
detail::parser_callback_t<basic_json>cb = nullptr,
const bool allow_exceptions = true,
const bool ignore_comments = false
)
)
{
return ::nlohmann::detail::parser<basic_json, InputAdapterType>(std::move(adapter),
std::move(cb), allow_exceptions, ignore_comments);
Expand Down Expand Up @@ -24662,7 +24748,7 @@ template<>
inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept(
is_nothrow_move_constructible<nlohmann::json>::value and
is_nothrow_move_assignable<nlohmann::json>::value
)
)
{
j1.swap(j2);
}
Expand Down
1 change: 1 addition & 0 deletions test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ set(files
src/unit-modifiers.cpp
src/unit-msgpack.cpp
src/unit-noexcept.cpp
src/unit-ordered_json.cpp
src/unit-pointer_access.cpp
src/unit-readme.cpp
src/unit-reference_access.cpp
Expand Down
79 changes: 79 additions & 0 deletions test/src/unit-ordered_json.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
__ _____ _____ _____
__| | __| | | | JSON for Modern C++ (test suite)
| | |__ | | | | | | version 3.8.0
|_____|_____|_____|_|___| https://github.com/nlohmann/json

Licensed under the MIT License <http://opensource.org/licenses/MIT>.
SPDX-License-Identifier: MIT
Copyright (c) 2013-2019 Niels Lohmann <http://nlohmann.me>.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "doctest_compatibility.h"

#include <nlohmann/json.hpp>
using nlohmann::json;
using nlohmann::ordered_json;


TEST_CASE("ordered_json")
{
json j;
ordered_json oj;

j["element3"] = 3;
j["element1"] = 1;
j["element2"] = 2;

oj["element3"] = 3;
oj["element1"] = 1;
oj["element2"] = 2;

CHECK(j.dump() == "{\"element1\":1,\"element2\":2,\"element3\":3}");
CHECK(oj.dump() == "{\"element3\":3,\"element1\":1,\"element2\":2}");

CHECK(j == json(oj));
CHECK(ordered_json(json(oj)) == ordered_json(j));

j.erase("element1");
oj.erase("element1");

CHECK(j.dump() == "{\"element2\":2,\"element3\":3}");
CHECK(oj.dump() == "{\"element3\":3,\"element2\":2}");

// remove again and nothing changes
j.erase("element1");
oj.erase("element1");

CHECK(j.dump() == "{\"element2\":2,\"element3\":3}");
CHECK(oj.dump() == "{\"element3\":3,\"element2\":2}");

// There are no dup keys cause constructor calls emplace...
json multi {{"z", 1}, {"m", 2}, {"m", 3}, {"y", 4}, {"m", 5}};
CHECK(multi.size() == 3);
CHECK(multi.dump() == "{\"m\":2,\"y\":4,\"z\":1}");

ordered_json multi_ordered {{"z", 1}, {"m", 2}, {"m", 3}, {"y", 4}, {"m", 5}};
CHECK(multi_ordered.size() == 3);
CHECK(multi_ordered.dump() == "{\"z\":1,\"m\":2,\"y\":4}");
CHECK(multi_ordered.erase("m") == 1);
CHECK(multi_ordered.dump() == "{\"z\":1,\"y\":4}");
}