Skip to content

Commit

Permalink
Add get_optional json function
Browse files Browse the repository at this point in the history
  • Loading branch information
mlund committed Jul 1, 2024
1 parent 596eccc commit 27b2079
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/core.h
Original file line number Diff line number Diff line change
Expand Up @@ -254,4 +254,17 @@ class Electrolyte
void to_json(json& j, const Electrolyte& electrolyte);
std::optional<Electrolyte> 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<typename T>
std::optional<T> get_optional(const json &j, std::string_view key) {
if (const auto it = j.find(key); it != j.end()) {
return it->get<T>(); // may throw exception
}
return std::nullopt;
}

} // namespace Faunus

0 comments on commit 27b2079

Please sign in to comment.