Add char8_t* overload for _json and _json_pointer (#4963)

This commit is contained in:
Niels Lohmann
2025-10-25 07:56:05 +02:00
committed by GitHub
parent df263544ed
commit 29913ca760
6 changed files with 94 additions and 0 deletions

View File

@@ -19,6 +19,11 @@ using nlohmann::json;
#include <sstream>
#include <valarray>
#if defined(_WIN32)
#define NOMINMAX
#include <windows.h> // for GetACP()
#endif
namespace
{
struct SaxEventLogger : public nlohmann::json_sax<json>
@@ -213,6 +218,20 @@ class proxy_iterator
private:
iterator* m_it = nullptr;
};
// JSON_HAS_CPP_20
#if defined(__cpp_char8_t)
bool check_utf8()
{
#if defined(_WIN32)
// Runtime check of the active ANSI code page
// 65001 == UTF-8
return GetACP() == 65001;
#else
return true;
#endif
}
#endif
} // namespace
TEST_CASE("deserialization")
@@ -1132,6 +1151,31 @@ TEST_CASE("deserialization")
CHECK(object_count == 4);
}
}
// build with C++20
// JSON_HAS_CPP_20
#if defined(__cpp_char8_t)
SECTION("Using _json with char8_t literals #4945")
{
// Regular narrow string literal
const auto j1 = R"({"key": "value", "num": 42})"_json;
CHECK(j1["key"] == "value");
CHECK(j1["num"] == 42);
// UTF-8 prefixed literal (C++20 and later);
// MSVC may not set /utf-8, so we need to check
if (check_utf8())
{
const auto j2 = u8R"({"emoji": "😀", "msg": "hello"})"_json;
CHECK(j2["emoji"] == "😀");
CHECK(j2["msg"] == "hello");
}
const auto j3 = u8R"({"key": "value", "num": 42})"_json;
CHECK(j3["key"] == "value");
CHECK(j3["num"] == 42);
}
#endif
}
// select the types to test - char8_t is only available since C++20 if and only

View File

@@ -788,4 +788,18 @@ TEST_CASE("JSON pointers")
CHECK_FALSE(ptr_oj != ptr);
}
}
// build with C++20
// JSON_HAS_CPP_20
#if defined(__cpp_char8_t)
SECTION("Using _json_pointer with char8_t literals #4945")
{
const json j = R"({"a": {"b": {"c": 123}}})"_json;
const auto p1 = "/a/b/c"_json_pointer;
CHECK(j[p1] == 123);
const auto p2 = u8"/a/b/c"_json_pointer;
CHECK(j[p2] == 123);
}
#endif
}