From 27b2079f26ada24fe4dc656c26f9f7a800b850fb Mon Sep 17 00:00:00 2001 From: Mikael Lund Date: Mon, 1 Jul 2024 17:34:55 +0200 Subject: [PATCH] Add get_optional json function --- src/core.h | 13 +++++++++++++ 1 file changed, 13 insertions(+) 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