core-adapters 0.1.2
Third-party adapters for snicholls-core: nanobind helpers, nlohmann/json hooks, the snicholls_core Python package
Loading...
Searching...
No Matches
decimal_json.hpp File Reference

nlohmann/json hooks for snicholls::decimal: its exact canonical text, as a JSON string. More...

#include <optional>
#include <string>
#include <snicholls/core_adapters/nlohmann/json.hpp>
#include <snicholls/core/decimal.hpp>

Go to the source code of this file.

Functions

void snicholls::to_json (nlohmann::json &j, const decimal &d)
 Writes d as its canonical text, a JSON string.
 
void snicholls::from_json (const nlohmann::json &j, decimal &d)
 Reads canonical decimal text from a JSON string.
 

Detailed Description

nlohmann/json hooks for snicholls::decimal: its exact canonical text, as a JSON string.

Overview
nlohmann::json j = d; writes "72.5", "0.0000001", "-5.25": decimal::text(), the one canonical spelling. It is a JSON string, not a number, because a JSON number is read as a double by most consumers (JavaScript among them) and 0.1 has no exact double. j.get<snicholls::decimal>() reads the canonical text only (decimal::parse with decimal_syntax::canonical); a JSON number is refused rather than guessed at.
const auto strike = snicholls::decimal::parse("72.5").value();
const nlohmann::json j = {{"strike", strike}}; // {"strike":"72.5"}: a string, so it stays exact
std::printf("%s\n", j.dump().c_str());
const auto back = j.at("strike").get<snicholls::decimal>();
Relationships
Guarantees and contracts
  • Round trip for every decimal; the text is the same on every platform (no locale, no double).
  • to_json throws only std::bad_alloc.
Errors
snicholls::json_error: not a string; not canonical decimal text ("72.50", "+1", "1e5" are refused); more than 18 significant digits or an exponent outside [-18, 18].
Performance
Not benchmarked: decimal::text / decimal::parse plus one std::string.
Tests and demos
  • Tests: tests/nlohmann/decimal_json_test.cpp.
  • Demo: demos/nlohmann/decimal_json_demo.cpp.
Dependencies
CMake target snicholls::core_json.
Known issues and gotchas
  • A venue that sends strikes as JSON numbers needs its own reader: take the number's original text (nlohmann::json::parse with a callback, or a SAX handler) and decimal::parse it with decimal_syntax::plain.
Status
Experimental, pre-1.0.

Definition in file decimal_json.hpp.