|
Unit Conversion and Dimensional Analysis Library 3.6.1
A compile-time, header-only C++23 dimensional-analysis library
|
Opt-in nlohmann/json support: quantities serialize to and from JSON when <nlohmann/json.hpp> is visible before units.
The library integrates with nlohmann/json without taking a dependency on it. If your translation unit includes <nlohmann/json.hpp> before it includes a units header, the library defines to_json/from_json hooks so any quantity converts to and from a nlohmann::json value. If nlohmann/json is not present, the hooks are absent and the library is unaffected.
Related how-to guides: defining new units, math functions, chrono interop.
At the bottom of core.h the JSON hooks are guarded by __has_include:
The consequence is a strict include-order requirement: include <nlohmann/json.hpp> before any units header. The __has_include check runs while units is being compiled; the include-guard on nlohmann's header means that if you have already included it, the units-side #include <nlohmann/json.hpp> is a no-op and the hooks are defined. Include units first and nlohmann second, and the check may not see the header when it matters.
Note: there is no build-system dependency and no CMake option to toggle this. The feature is purely a compile-time, header-presence opt-in — projects that never include nlohmann/json compile exactly as before.
to_json writes the quantity's raw magnitude; from_json reconstructs the quantity from a numeric JSON value.
Quantities nest inside objects and arrays like any other JSON value:
Caveat: the JSON encoding is the bare magnitude — the unit is not stored in the JSON. to_json serializes u.raw(), and from_json reads a number and constructs the target type from it. The unit is fixed by the C++ type you deserialize into (j.get<meters<double>>() yields meters; j.get<feet<double>>() would read the same number as feet). Both peers must agree on the unit out of band; JSON alone does not disambiguate it.
Note: this integration is currently exercised only through the guarded examples/json_roundtrip.cpp and is not covered by the unit-test suite. The behavior above is documented and compiles as shown, but treat it as a lightly-tested convenience rather than a hardened, spec-guaranteed surface.