faunus
json_support.h
1 #pragma once
2 
3 #include <optional>
4 #include <string>
5 #include <tuple>
6 #include <nlohmann/json.hpp>
7 
8 namespace Faunus {
9 
10 using json = nlohmann::json;
11 
13  const std::string& filename);
14 
26 struct SingleUseJSON : public json
27 {
28  explicit SingleUseJSON(const json&);
29  [[nodiscard]] bool empty() const;
30  [[nodiscard]] size_type count(const std::string&) const;
31  [[nodiscard]] std::string dump(int = -1) const;
32  [[nodiscard]] bool is_object() const;
33 
34  void clear();
35  json at(const std::string&);
36  json operator[](const std::string&);
37  void erase(const std::string&);
38 
39  template <class T> T value(const std::string& key, const T& fallback)
40  {
41  return (count(key) > 0) ? at(key).get<T>() : fallback;
42  }
43 };
44 
45 double roundValue(double value,
46  int number_of_digits = 3);
47 void roundJSON(json& j,
48  int number_of_digits = 3);
49 double getValueInfinity(
50  const json& j,
51  const std::string& key);
52 
64 std::tuple<const std::string&, const json&> jsonSingleItem(const json& j);
65 
71 template <typename T> std::optional<T> get_optional(const json& j, std::string_view key)
72 {
73  if (const auto it = j.find(key); it != j.end()) {
74  return it->get<T>(); // may throw exception
75  }
76  return std::nullopt;
77 }
78 
79 } // namespace Faunus
nlohmann::json json
JSON object.
Definition: json_support.h:10
double T
floating point size
Definition: units.h:73
json loadJSON(const std::string &filename)
Read json filename into json object (w. syntax check)
std::optional< T > get_optional(const json &j, std::string_view key)
Extract JSON value associated with key into std::optional
Definition: json_support.h:71
std::tuple< const std::string &, const json & > jsonSingleItem(const json &j)
Returns a key-value pair from a JSON object which contains a single key.
void roundJSON(json &j, int number_of_digits=3)
Round float objects to n number of significant digits.
Cell list class templates.
Definition: actions.cpp:11
double roundValue(double value, int number_of_digits=3)
Round to n number of significant digits.
Like json, but delete entries after access.
Definition: json_support.h:26
double getValueInfinity(const json &j, const std::string &key)
Extract floating point from json and allow for &#39;inf&#39; and &#39;-inf&#39;.