mirror of
https://github.com/nlohmann/json.git
synced 2026-10-26 15:58:55 +00:00
json_view: from_json() of the macros reads views directly
get<T>() and get_to() of a view call T's from_json() with the view itself when that from_json() accepts views but not an unrelated probe type, and fall back to materialize() otherwise. The from_json() functions of the NLOHMANN_DEFINE_TYPE_*, NLOHMANN_DEFINE_DERIVED_TYPE_* and NLOHMANN_JSON_SERIALIZE_ENUM(_STRICT) macros accept basic_json values and views; a derived type whose base reads only json reads the base part through materialize(). The library's own from_json() overloads are not called with views: from_json() of a view (and of the probe) only looks up functions by ADL. New public trait nlohmann::is_json_view<T>, and the member type basic_json_type of basic_json_view. With duplicate keys, the members of such a T are those the view's lookups find (the first ones). bench_decode.cpp measures decoding into structs (4-6x faster than materialize().get<T>() on twitter, citm_catalog, and synthetic records). Signed-off-by: Niels Lohmann <mail@nlohmann.me>
This commit is contained in:
23 files changed
+1342
-130
No files matched your search
@@ -59,6 +59,12 @@ An editable `json_document` edits in place; yyjson copies its immutable document
|
||||
(`yyjson_doc_mut_copy`); Boost.JSON and `json::parse` build mutable DOMs; simdjson cannot edit a document. All
|
||||
outputs are checked to describe the same value.
|
||||
|
||||
`bench_decode.cpp` measures decoding into structs whose `from_json()` comes from the `NLOHMANN_DEFINE_TYPE_*` macros
|
||||
(twitter statuses, citm_catalog performances, and 20,000 synthetic records): `get<T>()` on a view, which reads the
|
||||
view directly, against `materialize().get<T>()`, `json::parse` plus `get<T>()`, and `get<T>()` on an already parsed
|
||||
`json` value. Only nlohmann/json takes part, as the other libraries have no comparable mapping; all engines are
|
||||
checked to decode the same values.
|
||||
|
||||
Before anything is timed, all engines must accept each document and agree on the traversal: the number of values, the
|
||||
bytes of all strings and keys, and the sum of all numbers. All engines run interleaved in every round, and the best
|
||||
round is reported, as time and as a factor of the `json_view` time (below 1 means faster than `json_view`). Each timed
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
// __ _____ _____ _____
|
||||
// __| | __| | | | JSON for Modern C++ (supporting code)
|
||||
// | | |__ | | | | | | version 3.12.0
|
||||
// |_____|_____|_____|_|___| https://github.com/nlohmann/json
|
||||
//
|
||||
// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me>
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Decoding into structs: the same types, with from_json() generated by the
|
||||
// NLOHMANN_DEFINE_TYPE_* macros, read three ways. Only nlohmann/json takes
|
||||
// part; the other libraries have no comparable mapping.
|
||||
//
|
||||
// view json_document::parse, then get<T>() on the view (from_json reads the view)
|
||||
// materialize json_document::parse, then materialize().get<T>() (a json value first)
|
||||
// json::parse json::parse, then get<T>()
|
||||
// json::get get<T>() on an already parsed json value (the decoding alone)
|
||||
//
|
||||
// Documents: twitter (the statuses with their users and hashtags), citm_catalog
|
||||
// (the performances with their seat categories), and a synthetic document of
|
||||
// 20,000 nested records.
|
||||
//
|
||||
// Build: see README.md (same flags as bench_view.cpp).
|
||||
#include <nlohmann/json_view.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <functional>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
using nlohmann::json;
|
||||
using nlohmann::json_document;
|
||||
|
||||
static volatile std::size_t g_sink;
|
||||
|
||||
namespace twitter
|
||||
{
|
||||
struct hashtag
|
||||
{
|
||||
std::string text;
|
||||
std::vector<int> indices;
|
||||
};
|
||||
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(hashtag, text, indices)
|
||||
|
||||
struct entities
|
||||
{
|
||||
std::vector<hashtag> hashtags;
|
||||
};
|
||||
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(entities, hashtags)
|
||||
|
||||
struct user
|
||||
{
|
||||
std::uint64_t id = 0;
|
||||
std::string screen_name;
|
||||
std::string description;
|
||||
std::int64_t followers_count = 0;
|
||||
};
|
||||
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(user, id, screen_name, description, followers_count)
|
||||
|
||||
struct status
|
||||
{
|
||||
std::uint64_t id = 0;
|
||||
std::string text;
|
||||
user user;
|
||||
entities entities;
|
||||
std::int64_t retweet_count = 0;
|
||||
std::int64_t favorite_count = 0;
|
||||
};
|
||||
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(status, id, text, user, entities, retweet_count, favorite_count)
|
||||
|
||||
struct document
|
||||
{
|
||||
std::vector<status> statuses;
|
||||
};
|
||||
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(document, statuses)
|
||||
|
||||
std::size_t digest(const document& d)
|
||||
{
|
||||
std::size_t n = 0;
|
||||
for (const auto& s : d.statuses)
|
||||
{
|
||||
n += s.text.size() + s.user.screen_name.size() + s.entities.hashtags.size() + static_cast<std::size_t>(s.retweet_count);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
} // namespace twitter
|
||||
|
||||
namespace citm
|
||||
{
|
||||
struct area
|
||||
{
|
||||
std::int64_t areaId = 0;
|
||||
std::vector<std::int64_t> blockIds;
|
||||
};
|
||||
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(area, areaId, blockIds)
|
||||
|
||||
struct seat_category
|
||||
{
|
||||
std::vector<area> areas;
|
||||
std::int64_t seatCategoryId = 0;
|
||||
};
|
||||
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(seat_category, areas, seatCategoryId)
|
||||
|
||||
struct performance
|
||||
{
|
||||
std::int64_t id = 0;
|
||||
std::int64_t eventId = 0;
|
||||
std::vector<seat_category> seatCategories;
|
||||
std::int64_t start = 0;
|
||||
std::string venueCode;
|
||||
};
|
||||
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(performance, id, eventId, seatCategories, start, venueCode)
|
||||
|
||||
struct document
|
||||
{
|
||||
std::vector<performance> performances;
|
||||
};
|
||||
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(document, performances)
|
||||
|
||||
std::size_t digest(const document& d)
|
||||
{
|
||||
std::size_t n = 0;
|
||||
for (const auto& p : d.performances)
|
||||
{
|
||||
n += p.seatCategories.size() + p.venueCode.size() + static_cast<std::size_t>(p.start % 1000);
|
||||
for (const auto& c : p.seatCategories)
|
||||
{
|
||||
n += c.areas.size();
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
} // namespace citm
|
||||
|
||||
namespace synthetic
|
||||
{
|
||||
struct position
|
||||
{
|
||||
double x = 0;
|
||||
double y = 0;
|
||||
};
|
||||
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(position, x, y)
|
||||
|
||||
struct child
|
||||
{
|
||||
std::int64_t id = 0;
|
||||
std::string label;
|
||||
bool active = false;
|
||||
};
|
||||
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(child, id, label, active)
|
||||
|
||||
struct record
|
||||
{
|
||||
std::int64_t id = 0;
|
||||
std::string name;
|
||||
std::vector<std::string> tags;
|
||||
position pos;
|
||||
std::vector<child> children;
|
||||
};
|
||||
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(record, id, name, tags, pos, children)
|
||||
|
||||
struct document
|
||||
{
|
||||
std::vector<record> records;
|
||||
};
|
||||
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(document, records)
|
||||
|
||||
std::string make_text(std::size_t n)
|
||||
{
|
||||
std::string s = "{\"records\":[";
|
||||
for (std::size_t i = 0; i < n; ++i)
|
||||
{
|
||||
const std::string id = std::to_string(i);
|
||||
s += (i == 0 ? "" : ",");
|
||||
s += "{\"id\":" + id + ",\"name\":\"record number " + id + "\",\"tags\":[\"alpha\",\"beta\",\"gamma\"],";
|
||||
s += "\"pos\":{\"x\":" + id + ".25,\"y\":-" + id + ".5},\"children\":[";
|
||||
for (std::size_t k = 0; k < 3; ++k)
|
||||
{
|
||||
s += (k == 0 ? "" : ",");
|
||||
s += "{\"id\":" + std::to_string(i * 3 + k) + ",\"label\":\"child " + std::to_string(k) + "\",\"active\":" + (k % 2 == 0 ? "true" : "false") + "}";
|
||||
}
|
||||
s += "]}";
|
||||
}
|
||||
s += "]}";
|
||||
return s;
|
||||
}
|
||||
|
||||
std::size_t digest(const document& d)
|
||||
{
|
||||
std::size_t n = 0;
|
||||
for (const auto& r : d.records)
|
||||
{
|
||||
n += r.name.size() + r.tags.size() + r.children.size() + static_cast<std::size_t>(r.pos.x);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
} // namespace synthetic
|
||||
|
||||
namespace
|
||||
{
|
||||
std::string read_file(const std::string& p)
|
||||
{
|
||||
std::ifstream f(p, std::ios::binary);
|
||||
if (!f)
|
||||
{
|
||||
std::fprintf(stderr, "cannot open %s\n", p.c_str());
|
||||
std::exit(1);
|
||||
}
|
||||
std::stringstream ss;
|
||||
ss << f.rdbuf();
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
double time_ns(const std::function<void()>& f)
|
||||
{
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
f();
|
||||
const auto t1 = std::chrono::steady_clock::now();
|
||||
return static_cast<double>(std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count());
|
||||
}
|
||||
|
||||
struct engine
|
||||
{
|
||||
std::string name;
|
||||
std::function<std::size_t()> run;
|
||||
};
|
||||
|
||||
template<typename Document>
|
||||
std::vector<engine> engines(const std::string& text, const json& parsed)
|
||||
{
|
||||
return
|
||||
{
|
||||
{"view", [&text] { const json_document d = json_document::parse(text); return digest(d.root().get<Document>()); }},
|
||||
{"materialize", [&text] { const json_document d = json_document::parse(text); return digest(d.root().materialize().get<Document>()); }},
|
||||
{"json::parse", [&text] { return digest(json::parse(text).get<Document>()); }},
|
||||
{"json::get", [&parsed] { return digest(parsed.get<Document>()); }},
|
||||
};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
if (argc < 2)
|
||||
{
|
||||
std::fprintf(stderr, "usage: %s <json_test_data directory> [rounds]\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
const std::string dir = argv[1];
|
||||
const int rounds = argc > 2 ? std::max(1, std::atoi(argv[2])) : 30;
|
||||
|
||||
struct document_case
|
||||
{
|
||||
std::string name;
|
||||
std::string text;
|
||||
json parsed;
|
||||
std::vector<engine> engines;
|
||||
};
|
||||
std::vector<document_case> cases;
|
||||
cases.push_back({"twitter", read_file(dir + "/nativejson-benchmark/twitter.json"), json(), {}});
|
||||
cases.push_back({"citm_catalog", read_file(dir + "/nativejson-benchmark/citm_catalog.json"), json(), {}});
|
||||
cases.push_back({"synthetic", synthetic::make_text(20000), json(), {}});
|
||||
for (auto& c : cases)
|
||||
{
|
||||
c.parsed = json::parse(c.text);
|
||||
}
|
||||
cases[0].engines = engines<twitter::document>(cases[0].text, cases[0].parsed);
|
||||
cases[1].engines = engines<citm::document>(cases[1].text, cases[1].parsed);
|
||||
cases[2].engines = engines<synthetic::document>(cases[2].text, cases[2].parsed);
|
||||
|
||||
std::FILE* csv = std::fopen("bench_decode.csv", "w");
|
||||
if (csv == nullptr)
|
||||
{
|
||||
std::perror("bench_decode.csv");
|
||||
return 1;
|
||||
}
|
||||
std::fprintf(csv, "doc,bytes,engine,ns\n");
|
||||
for (const auto& c : cases)
|
||||
{
|
||||
// all engines must decode the same values
|
||||
const std::size_t expected = c.engines[0].run();
|
||||
bool ok = true;
|
||||
for (const auto& e : c.engines)
|
||||
{
|
||||
ok = ok && e.run() == expected;
|
||||
}
|
||||
std::vector<double> best(c.engines.size(), 1e300);
|
||||
for (int r = 0; r < rounds; ++r)
|
||||
{
|
||||
for (std::size_t k = 0; k < c.engines.size(); ++k)
|
||||
{
|
||||
g_sink = c.engines[k].run(); // untimed: see bench_view.cpp
|
||||
best[k] = std::min(best[k], time_ns([&] { g_sink = c.engines[k].run(); }));
|
||||
}
|
||||
}
|
||||
std::printf("%-13s %-7s %s", c.name.c_str(), "decode", ok ? "" : "[MISMATCH] ");
|
||||
for (std::size_t k = 0; k < c.engines.size(); ++k)
|
||||
{
|
||||
const double us = best[k] / 1000.0;
|
||||
std::printf(" %s %.*fus (%.2fx)", c.engines[k].name.c_str(), us < 10 ? 3 : (us < 1000 ? 1 : 0), us, best[k] / best[0]);
|
||||
std::fprintf(csv, "%s,%zu,%s,%.1f\n", c.name.c_str(), c.text.size(), c.engines[k].name.c_str(), best[k]);
|
||||
}
|
||||
std::printf("\n");
|
||||
}
|
||||
std::fclose(csv);
|
||||
return 0;
|
||||
}
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
"""Compare json_view with yyjson, simdjson, Boost.JSON, and json::parse.
|
||||
|
||||
Builds bench_view.cpp, bench_corpus.cpp, and bench_edit.cpp against the include/ directory of
|
||||
Builds bench_view.cpp, bench_corpus.cpp, bench_edit.cpp, and bench_decode.cpp against the include/ directory of
|
||||
this checkout, runs them, and writes the results with everything needed to
|
||||
reproduce them (date, commit, CPU, OS, compiler, library versions, flags) to
|
||||
results/<date>-<host>.md and .csv next to this script.
|
||||
@@ -283,7 +283,7 @@ def main():
|
||||
objects.append(obj)
|
||||
|
||||
binaries = {}
|
||||
for bench in ['bench_view', 'bench_corpus', 'bench_edit']:
|
||||
for bench in ['bench_view', 'bench_corpus', 'bench_edit', 'bench_decode']:
|
||||
exe = os.path.join(args.build_dir, bench)
|
||||
run(cxx + flags + include + [os.path.join(HERE, bench + '.cpp')] + objects + link + ['-o', exe])
|
||||
binaries[bench] = exe
|
||||
@@ -297,6 +297,8 @@ def main():
|
||||
capture_output=True, text=True).stdout
|
||||
outputs['bench_edit'] = run([binaries['bench_edit'], args.data, str(max(1, args.rounds // 2))], cwd=args.build_dir,
|
||||
capture_output=True, text=True).stdout
|
||||
outputs['bench_decode'] = run([binaries['bench_decode'], args.data, str(max(1, args.rounds // 2))], cwd=args.build_dir,
|
||||
capture_output=True, text=True).stdout
|
||||
for name, text in outputs.items():
|
||||
print(text)
|
||||
|
||||
@@ -330,7 +332,7 @@ def main():
|
||||
f.write(f'\n## {name}\n\n```\n{text.rstrip()}\n```\n')
|
||||
with open(stem + '.csv', 'w', encoding='utf-8') as out:
|
||||
out.write(''.join(f'# {key}: {value}\n' for key, value in meta))
|
||||
for name in ['bench_view', 'bench_corpus', 'bench_edit']:
|
||||
for name in ['bench_view', 'bench_corpus', 'bench_edit', 'bench_decode']:
|
||||
path = os.path.join(args.build_dir, name + '.csv')
|
||||
if os.path.isfile(path):
|
||||
with open(path, encoding='utf-8') as f:
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
// __ _____ _____ _____
|
||||
// __| | __| | | | JSON for Modern C++ (supporting code)
|
||||
// | | |__ | | | | | | version 3.12.0
|
||||
// |_____|_____|_____|_|___| https://github.com/nlohmann/json
|
||||
//
|
||||
// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me>
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
#include <nlohmann/json_view.hpp>
|
||||
using nlohmann::json;
|
||||
using nlohmann::json_document;
|
||||
using nlohmann::json_view;
|
||||
using nlohmann::json_editable_document;
|
||||
using nlohmann::ordered_json_document;
|
||||
|
||||
#include "json_view_test_helpers.hpp"
|
||||
#if !defined(JSON_NOEXCEPTION)
|
||||
using json_view_test::exception_of_call;
|
||||
#endif
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <forward_list>
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <utility>
|
||||
#include <valarray>
|
||||
#include <vector>
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
#include <optional>
|
||||
#endif
|
||||
|
||||
// The from_json() functions of the NLOHMANN_DEFINE_TYPE_* and
|
||||
// NLOHMANN_JSON_SERIALIZE_ENUM macros read views directly; other from_json()
|
||||
// functions get the value of materialize().
|
||||
|
||||
namespace view_from_json
|
||||
{
|
||||
struct point
|
||||
{
|
||||
int x = 0;
|
||||
int y = 0;
|
||||
NLOHMANN_DEFINE_TYPE_INTRUSIVE(point, x, y)
|
||||
};
|
||||
|
||||
struct shape
|
||||
{
|
||||
std::string name;
|
||||
std::vector<point> points;
|
||||
point center;
|
||||
std::map<std::string, point> named;
|
||||
NLOHMANN_DEFINE_TYPE_INTRUSIVE(shape, name, points, center, named)
|
||||
};
|
||||
|
||||
struct with_defaults
|
||||
{
|
||||
int a = 1;
|
||||
std::string b = "default";
|
||||
std::vector<int> c = {1, 2};
|
||||
};
|
||||
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(with_defaults, a, b, c)
|
||||
|
||||
struct with_names
|
||||
{
|
||||
int value = 0;
|
||||
std::string text;
|
||||
};
|
||||
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_NAMES(with_names, "Value", value, "Text", text)
|
||||
|
||||
struct empty
|
||||
{
|
||||
NLOHMANN_DEFINE_TYPE_INTRUSIVE(empty)
|
||||
};
|
||||
|
||||
enum class color
|
||||
{
|
||||
red,
|
||||
green,
|
||||
blue
|
||||
};
|
||||
NLOHMANN_JSON_SERIALIZE_ENUM(color,
|
||||
{
|
||||
{color::red, "red"},
|
||||
{color::green, "green"},
|
||||
{color::blue, nullptr},
|
||||
})
|
||||
|
||||
enum class strict_color
|
||||
{
|
||||
red,
|
||||
green
|
||||
};
|
||||
NLOHMANN_JSON_SERIALIZE_ENUM_STRICT(strict_color,
|
||||
{
|
||||
{strict_color::red, "red"},
|
||||
{strict_color::green, 1},
|
||||
})
|
||||
|
||||
struct base
|
||||
{
|
||||
int id = 0;
|
||||
NLOHMANN_DEFINE_TYPE_INTRUSIVE(base, id)
|
||||
};
|
||||
|
||||
struct derived : base
|
||||
{
|
||||
color c = color::red;
|
||||
NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE(derived, base, c)
|
||||
};
|
||||
|
||||
struct derived_with_defaults : base
|
||||
{
|
||||
std::string label = "none";
|
||||
NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT(derived_with_defaults, base, label)
|
||||
};
|
||||
|
||||
// a base whose from_json() is written for json only: the derived type reads
|
||||
// its own members from the view and the base part from materialize()
|
||||
struct legacy_base
|
||||
{
|
||||
int id = 0;
|
||||
};
|
||||
// NOLINTNEXTLINE(misc-use-internal-linkage): found by ADL, like the from_json() functions of users
|
||||
inline void from_json(const json& j, legacy_base& b)
|
||||
{
|
||||
b.id = j.at("id").get<int>();
|
||||
}
|
||||
|
||||
struct derived_from_legacy : legacy_base
|
||||
{
|
||||
int extra = 0;
|
||||
};
|
||||
NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE(derived_from_legacy, legacy_base, extra)
|
||||
|
||||
// from_json() for json only: converted through materialize()
|
||||
struct legacy
|
||||
{
|
||||
int v = 0;
|
||||
};
|
||||
// NOLINTNEXTLINE(misc-use-internal-linkage): found by ADL, like the from_json() functions of users
|
||||
inline void from_json(const json& j, legacy& l)
|
||||
{
|
||||
l.v = j.at("v").get<int>();
|
||||
}
|
||||
|
||||
// an unconstrained from_json() template, as in the documentation of
|
||||
// arbitrary type conversions: converted through materialize()
|
||||
struct unconstrained
|
||||
{
|
||||
int v = 0;
|
||||
};
|
||||
template<typename BasicJsonType>
|
||||
// NOLINTNEXTLINE(misc-use-internal-linkage): found by ADL, like the from_json() functions of users
|
||||
void from_json(const BasicJsonType& j, unconstrained& u)
|
||||
{
|
||||
u.v = j.at("v").template get<int>();
|
||||
}
|
||||
|
||||
// a from_json() constrained by the user to views and json: reads the view
|
||||
struct constrained
|
||||
{
|
||||
int v = 0;
|
||||
};
|
||||
template < typename J, typename std::enable_if < nlohmann::is_json_view<J>::value || std::is_same<J, json>::value, int >::type = 0 >
|
||||
// NOLINTNEXTLINE(misc-use-internal-linkage): found by ADL, like the from_json() functions of users
|
||||
void from_json(const J& j, constrained& c)
|
||||
{
|
||||
c.v = j.at("v").template get<int>();
|
||||
}
|
||||
} // namespace view_from_json
|
||||
|
||||
namespace
|
||||
{
|
||||
template<typename T, typename View = json_view>
|
||||
struct reads_view : nlohmann::detail::has_view_from_json<nlohmann::adl_serializer<T, void>, View, T> {};
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("json_view from_json")
|
||||
{
|
||||
using namespace view_from_json; // NOLINT(google-build-using-namespace)
|
||||
|
||||
SECTION("which from_json() functions read views")
|
||||
{
|
||||
static_assert(reads_view<point>::value, "macro types read views");
|
||||
static_assert(reads_view<shape>::value, "macro types read views");
|
||||
static_assert(reads_view<with_defaults>::value, "macro types read views");
|
||||
static_assert(reads_view<with_names>::value, "macro types read views");
|
||||
static_assert(reads_view<empty>::value, "macro types read views");
|
||||
static_assert(reads_view<derived>::value, "macro types read views");
|
||||
static_assert(reads_view<derived_from_legacy>::value, "macro types read views");
|
||||
static_assert(reads_view<color>::value, "enum macro types read views");
|
||||
static_assert(reads_view<strict_color>::value, "enum macro types read views");
|
||||
static_assert(reads_view<constrained>::value, "constrained from_json() reads views");
|
||||
static_assert(reads_view<point, nlohmann::json_editable_view>::value, "editable views as well");
|
||||
static_assert(reads_view<point, nlohmann::ordered_json_view>::value, "views of ordered_json as well");
|
||||
static_assert(!reads_view<legacy>::value, "from_json() for json");
|
||||
static_assert(!reads_view<legacy_base>::value, "from_json() for json");
|
||||
static_assert(!reads_view<unconstrained>::value, "unconstrained from_json()");
|
||||
|
||||
static_assert(nlohmann::is_json_view<json_view>::value, "is_json_view");
|
||||
static_assert(nlohmann::is_json_view<nlohmann::ordered_json_editable_view>::value, "is_json_view");
|
||||
static_assert(!nlohmann::is_json_view<json>::value, "is_json_view");
|
||||
static_assert(!nlohmann::is_json_view<json_document>::value, "is_json_view");
|
||||
static_assert(!nlohmann::is_json_view<int>::value, "is_json_view");
|
||||
}
|
||||
|
||||
SECTION("the library's own conversions are not called with a view (and the probe compiles for them)")
|
||||
{
|
||||
// these go through materialize() (vectors, maps with string keys,
|
||||
// strings, and numbers are converted by the view itself)
|
||||
static_assert(!reads_view<std::list<int>>::value, "std types");
|
||||
static_assert(!reads_view<std::deque<point>>::value, "std types");
|
||||
static_assert(!reads_view<std::set<std::string>>::value, "std types");
|
||||
static_assert(!reads_view<std::unordered_set<int>>::value, "std types");
|
||||
static_assert(!reads_view<std::forward_list<int>>::value, "std types");
|
||||
static_assert(!reads_view<std::valarray<double>>::value, "std types");
|
||||
static_assert(!reads_view<std::array<int, 3>>::value, "std types");
|
||||
static_assert(!reads_view<std::pair<int, std::string>>::value, "std types");
|
||||
static_assert(!reads_view<std::tuple<int, bool, point>>::value, "std types");
|
||||
static_assert(!reads_view<std::map<int, int>>::value, "std types");
|
||||
static_assert(!reads_view<std::unordered_map<int, point>>::value, "std types");
|
||||
static_assert(!reads_view<std::map<color, int>>::value, "std types");
|
||||
static_assert(!reads_view<std::map<std::string, int>>::value, "std types");
|
||||
static_assert(!reads_view<std::vector<point>>::value, "std types");
|
||||
static_assert(!reads_view<std::vector<bool>>::value, "std types");
|
||||
static_assert(!reads_view<std::vector<std::uint8_t>>::value, "std types");
|
||||
static_assert(!reads_view<std::string>::value, "std types");
|
||||
static_assert(!reads_view<int>::value, "std types");
|
||||
static_assert(!reads_view<bool>::value, "std types");
|
||||
static_assert(!reads_view<double>::value, "std types");
|
||||
static_assert(!reads_view<std::nullptr_t>::value, "std types");
|
||||
static_assert(!reads_view<json>::value, "std types");
|
||||
static_assert(!reads_view<json::binary_t>::value, "std types");
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
static_assert(!reads_view<std::optional<point>>::value, "std types");
|
||||
#endif
|
||||
CHECK(true);
|
||||
}
|
||||
|
||||
SECTION("macro types")
|
||||
{
|
||||
const json_document d = json_document::parse(R"({"name": "s", "points": [{"x": 1, "y": 2}, {"x": 3, "y": 4}],
|
||||
"center": {"x": 5, "y": 6}, "named": {"a": {"x": 7, "y": 8}}})");
|
||||
const shape s = d.root().get<shape>();
|
||||
CHECK(s.name == "s");
|
||||
CHECK(s.points.size() == 2);
|
||||
CHECK(s.points[1].y == 4);
|
||||
CHECK(s.center.x == 5);
|
||||
CHECK(s.named.at("a").y == 8);
|
||||
|
||||
point p;
|
||||
d.root()["center"].get_to(p);
|
||||
CHECK(p.x == 5);
|
||||
CHECK(p.y == 6);
|
||||
|
||||
static_cast<void>(d.root()["center"].get<empty>());
|
||||
}
|
||||
|
||||
SECTION("defaults and names")
|
||||
{
|
||||
const json_document d = json_document::parse(R"({"a": 5, "Value": 3, "Text": "t"})");
|
||||
const with_defaults w = d.root().get<with_defaults>();
|
||||
CHECK(w.a == 5);
|
||||
CHECK(w.b == "default");
|
||||
CHECK(w.c == std::vector<int> {1, 2});
|
||||
const json_document null_document = json_document::parse("null");
|
||||
CHECK(null_document.root().get<with_defaults>().a == 1);
|
||||
const with_names n = d.root().get<with_names>();
|
||||
CHECK(n.value == 3);
|
||||
CHECK(n.text == "t");
|
||||
}
|
||||
|
||||
SECTION("enums")
|
||||
{
|
||||
const json_document d = json_document::parse(R"(["green", null, "purple", 1, "red"])");
|
||||
CHECK(d.root()[0].get<color>() == color::green);
|
||||
CHECK(d.root()[1].get<color>() == color::blue);
|
||||
CHECK(d.root()[2].get<color>() == color::red); // unknown values map to the first entry
|
||||
CHECK(d.root()[3].get<strict_color>() == strict_color::green);
|
||||
CHECK(d.root()[4].get<strict_color>() == strict_color::red);
|
||||
#if !defined(JSON_NOEXCEPTION)
|
||||
const json j = d.root().materialize();
|
||||
CHECK(exception_of_call([&] { static_cast<void>(d.root()[2].get<strict_color>()); }) == "[json.exception.out_of_range.410] enum value out of range for strict_color: \"purple\"");
|
||||
#if !JSON_DIAGNOSTICS
|
||||
CHECK(exception_of_call([&] { static_cast<void>(d.root()[2].get<strict_color>()); }) == exception_of_call([&] { static_cast<void>(j[2].get<strict_color>()); }));
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
SECTION("derived types")
|
||||
{
|
||||
const json_document d = json_document::parse(R"({"id": 7, "c": "green", "extra": 3})");
|
||||
const derived x = d.root().get<derived>();
|
||||
CHECK(x.id == 7);
|
||||
CHECK(x.c == color::green);
|
||||
const derived_with_defaults y = d.root().get<derived_with_defaults>();
|
||||
CHECK(y.id == 7);
|
||||
CHECK(y.label == "none");
|
||||
const derived_from_legacy z = d.root().get<derived_from_legacy>();
|
||||
CHECK(z.id == 7);
|
||||
CHECK(z.extra == 3);
|
||||
}
|
||||
|
||||
SECTION("other from_json() functions get the value of materialize()")
|
||||
{
|
||||
const json_document d = json_document::parse(R"({"v": 4})");
|
||||
CHECK(d.root().get<legacy>().v == 4);
|
||||
CHECK(d.root().get<unconstrained>().v == 4);
|
||||
CHECK(d.root().get<constrained>().v == 4);
|
||||
legacy l;
|
||||
d.root().get_to(l);
|
||||
CHECK(l.v == 4);
|
||||
}
|
||||
|
||||
SECTION("duplicate keys: members are looked up in the view, where the first one wins")
|
||||
{
|
||||
const json_document d = json_document::parse(R"({"x": 1, "y": 2, "x": 3})");
|
||||
CHECK(d.root().get<point>().x == 1);
|
||||
// materialize() keeps the last value, like parse()
|
||||
CHECK(d.root().materialize().get<point>().x == 3);
|
||||
}
|
||||
|
||||
SECTION("editable documents and ordered_json")
|
||||
{
|
||||
json_editable_document e = json_editable_document::parse(R"({"x": 1, "y": 2})");
|
||||
e.set(e.root(), "x", 10);
|
||||
CHECK(e.root().get<point>().x == 10);
|
||||
const ordered_json_document o = ordered_json_document::parse(R"({"name": "o", "points": [], "center": {"x": 1, "y": 2}, "named": {}})");
|
||||
CHECK(o.root().get<shape>().center.y == 2);
|
||||
}
|
||||
|
||||
#if !defined(JSON_NOEXCEPTION) && !JSON_DIAGNOSTICS
|
||||
SECTION("errors are those of the same conversion of a json value")
|
||||
{
|
||||
// (with JSON_DIAGNOSTICS, those of json name the path of the value)
|
||||
const json_document d = json_document::parse(R"([{"x": 1}, {"x": "1", "y": 2}, [1, 2], {"id": "7", "c": "red"}])");
|
||||
const json j = d.root().materialize();
|
||||
for (std::size_t i = 0; i < 3; ++i)
|
||||
{
|
||||
CAPTURE(i)
|
||||
CHECK(exception_of_call([&] { static_cast<void>(d.root()[i].get<point>()); }) == exception_of_call([&] { static_cast<void>(j[i].get<point>()); }));
|
||||
}
|
||||
CHECK(exception_of_call([&] { static_cast<void>(d.root()[3].get<derived>()); }) == exception_of_call([&] { static_cast<void>(j[3].get<derived>()); }));
|
||||
}
|
||||
#endif
|
||||
}
|
||||
Reference in new issue
Block a user