PolyFEM
Loading...
Searching...
No Matches
YamlToJson.cpp
Go to the documentation of this file.
1// Original source code from https://github.com/mircodezorzi/tojson (MIT License)
2
3#include "YamlToJson.hpp"
4
6
7#include <yaml-cpp/yaml.h>
8
9namespace polyfem::io
10{
11 namespace
12 {
13 inline nlohmann::json parse_scalar(const YAML::Node &node)
14 {
15 int i;
16 double d;
17 bool b;
18 std::string s;
19
20 // handle special bool values in YAML: y, yes, on, n, no, off
21 if (YAML::convert<std::string>::decode(node, s) && s == "y")
22 log_and_throw_error("ambiguous yaml value: {} could be bool or string", s);
23
24 if (YAML::convert<int>::decode(node, i))
25 return i;
26 if (YAML::convert<double>::decode(node, d))
27 return d;
28 if (YAML::convert<bool>::decode(node, b))
29 return b;
30 if (YAML::convert<std::string>::decode(node, s))
31 return s;
32
33 return nullptr;
34 }
35
37 inline nlohmann::json yaml_to_json(const YAML::Node &root)
38 {
39 nlohmann::json j{};
40
41 switch (root.Type())
42 {
43 case YAML::NodeType::Null:
44 break;
45 case YAML::NodeType::Scalar:
46 return parse_scalar(root);
47 case YAML::NodeType::Sequence:
48 for (auto &&node : root)
49 j.emplace_back(yaml_to_json(node));
50 break;
51 case YAML::NodeType::Map:
52 for (auto &&it : root)
53 j[it.first.as<std::string>()] = yaml_to_json(it.second);
54 break;
55 default:
56 break;
57 }
58 return j;
59 }
60 } // namespace
61
62 json yaml_string_to_json(const std::string &yaml_str)
63 {
64 YAML::Node root = YAML::Load(yaml_str);
65 return yaml_to_json(root);
66 }
67
68 json yaml_file_to_json(const std::string &yaml_filepath)
69 {
70 YAML::Node root = YAML::LoadFile(yaml_filepath);
71 return yaml_to_json(root);
72 }
73} // namespace polyfem::io
json yaml_file_to_json(const std::string &yaml_filepath)
Load a YAML file to JSON.
json yaml_string_to_json(const std::string &yaml_str)
Convert YAML string to JSON.
nlohmann::json json
Definition Common.hpp:9
void log_and_throw_error(const std::string &msg)
Definition Logger.cpp:71