diff --git a/src/core.h b/src/core.h index da63ba660..0b96a0053 100644 --- a/src/core.h +++ b/src/core.h @@ -254,4 +254,17 @@ class Electrolyte void to_json(json& j, const Electrolyte& electrolyte); std::optional makeElectrolyte(const json& j); //!< Create ionic salt object from json +/// Extract JSON value associated with `key` into `std::optional` +/// +/// If the value does not exist, return `std::nullopt` +/// +/// @throws If value exists but cannot be extracted as `T`. +template +std::optional get_optional(const json &j, std::string_view key) { + if (const auto it = j.find(key); it != j.end()) { + return it->get(); // may throw exception + } + return std::nullopt; +} + } // namespace Faunus