Skip to content

Commit

Permalink
convert yaml to json
Browse files Browse the repository at this point in the history
  • Loading branch information
fantasy-peak committed Apr 10, 2023
1 parent 7eec46f commit 5fa70d6
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 0 deletions.
8 changes: 8 additions & 0 deletions example/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,13 @@ FetchContent_Declare(
)
FetchContent_MakeAvailable(yaml_cpp_struct)

FetchContent_Declare(
json
GIT_REPOSITORY https://github.com/nlohmann/json.git
GIT_TAG v3.11.2
)
FetchContent_MakeAvailable(json)

add_executable(example main.cpp)
target_include_directories(example PUBLIC ${CMAKE_BINARY_DIR}/_deps/visit_struct-src/include/;)
target_link_libraries(example
Expand All @@ -61,4 +68,5 @@ target_link_libraries(example
yaml_cpp_struct
pthread
spdlog::spdlog
nlohmann_json::nlohmann_json
)
4 changes: 4 additions & 0 deletions example/main.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// #define NOT_USE_YCS_INIT_VALUE
// #define OPEN_YAML_TO_JSON

#include <spdlog/spdlog.h>
#include <iostream>
Expand Down Expand Up @@ -194,5 +195,8 @@ int main(int, char** argv) {
spdlog::info("\n{}", to_string(cfg.value()));
auto [str, e] = yaml_cpp_struct::to_yaml(cfg.value());
spdlog::info("\n{}", str.value());
#ifdef OPEN_YAML_TO_JSON
spdlog::info("\n{}", yaml_cpp_struct::yaml_to_json(str.value()).dump());
#endif
return 0;
}
55 changes: 55 additions & 0 deletions include/yaml_cpp_struct.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,61 @@
#include <magic_enum.hpp>
#include <visit_struct/visit_struct.hpp>

#ifdef OPEN_YAML_TO_JSON

#include <nlohmann/json.hpp>

namespace yaml_cpp_struct {

inline nlohmann::json parse_scalar(const YAML::Node& node) {
int i;
double d;
bool b;
std::string s;

if (YAML::convert<int>::decode(node, i))
return i;
if (YAML::convert<double>::decode(node, d))
return d;
if (YAML::convert<bool>::decode(node, b))
return b;
if (YAML::convert<std::string>::decode(node, s))
return s;

return nullptr;
}

inline nlohmann::json yaml2json(const YAML::Node& root) {
nlohmann::json j{};
switch (root.Type()) {
case YAML::NodeType::Null:
break;
case YAML::NodeType::Scalar:
return parse_scalar(root);
case YAML::NodeType::Sequence:
for (auto&& node : root)
j.emplace_back(yaml2json(node));
break;
case YAML::NodeType::Map:
for (auto&& it : root) {
j[it.first.as<std::string>()] = yaml2json(it.second);
}
break;
default:
break;
}
return j;
}

[[nodiscard]] inline nlohmann::json yaml_to_json(const std::string& str) {
YAML::Node root = YAML::Load(str);
return yaml2json(root);
}

} // namespace yaml_cpp_struct

#endif

namespace yaml_cpp_struct {

template <typename... Args>
Expand Down

0 comments on commit 5fa70d6

Please sign in to comment.