Ginkgo  Generated from pipelines/1330831941 branch based on master. Ginkgo version 1.8.0
A numerical linear algebra library targeting many-core architectures
json_config.hpp
1 // SPDX-FileCopyrightText: 2017 - 2024 The Ginkgo authors
2 //
3 // SPDX-License-Identifier: BSD-3-Clause
4 
5 #ifndef GKO_PUBLIC_EXTENSIONS_CONFIG_JSON_CONFIG_HPP_
6 #define GKO_PUBLIC_EXTENSIONS_CONFIG_JSON_CONFIG_HPP_
7 
8 
9 #include <fstream>
10 #include <stdexcept>
11 #include <string>
12 
13 
14 #include <nlohmann/json.hpp>
15 
16 
17 #include <ginkgo/core/config/property_tree.hpp>
18 
19 
20 namespace gko {
21 namespace ext {
22 namespace config {
23 
24 
29 inline gko::config::pnode parse_json(const nlohmann::json& input)
30 {
31  const auto& dom = input;
32 
33  auto parse_array = [](const auto& arr) {
34  gko::config::pnode::array_type nodes;
35  for (auto it : arr) {
36  nodes.emplace_back(parse_json(it));
37  }
38  return gko::config::pnode{nodes};
39  };
40  auto parse_map = [](const auto& map) {
41  gko::config::pnode::map_type nodes;
42  for (auto& el : map.items()) {
43  nodes.emplace(el.key(), parse_json(el.value()));
44  }
45  return gko::config::pnode{nodes};
46  };
47  auto parse_data = [](const auto& data) {
48  if (data.is_number_integer()) {
49  return gko::config::pnode{data.template get<std::int64_t>()};
50  }
51  if (data.is_boolean()) {
52  return gko::config::pnode{data.template get<bool>()};
53  }
54  if (data.is_number_float()) {
55  return gko::config::pnode{data.template get<double>()};
56  }
57  if (data.is_string()) {
58  return gko::config::pnode{
59  std::string(data.template get<std::string>())};
60  }
61  throw std::runtime_error(
62  "property_tree can not handle the node with content: " +
63  data.dump());
64  };
65 
66  if (dom.is_array()) {
67  return parse_array(dom);
68  }
69  if (dom.is_object()) {
70  return parse_map(dom);
71  }
72  return parse_data(dom);
73 }
74 
75 
79 inline gko::config::pnode parse_json_file(std::string filename)
80 {
81  std::ifstream fstream(filename);
82  return parse_json(nlohmann::json::parse(fstream));
83 }
84 
85 
86 } // namespace config
87 } // namespace ext
88 } // namespace gko
89 
90 
91 #endif // GKO_PUBLIC_EXTENSIONS_CONFIG_JSON_CONFIG_HPP_
gko::config::pnode
pnode describes a tree of properties.
Definition: property_tree.hpp:28
gko
The Ginkgo namespace.
Definition: abstract_factory.hpp:20