Skip to content

Commit

Permalink
Merge pull request #1721 from ginkgo-project/feat/parse_json_string
Browse files Browse the repository at this point in the history
Add function to create gko::config::pnode from std::string, see #1721
  • Loading branch information
greole authored Dec 5, 2024
2 parents b7fa9a2 + 55997e4 commit 3d30c04
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
22 changes: 21 additions & 1 deletion extensions/test/config/json_config.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// SPDX-License-Identifier: BSD-3-Clause

#include <stdexcept>
#include <string>

#include <gtest/gtest.h>
#include <nlohmann/json.hpp>
Expand Down Expand Up @@ -54,7 +55,7 @@ TEST(JsonConfig, ReadInput)
{
const char json[] =
R"({"item": 4,
"array": [3.0, 4.5],
"array": [3.0, 4.5],
"map": {"bool": false}})";

auto d = nlohmann::json::parse(json);
Expand All @@ -72,6 +73,25 @@ TEST(JsonConfig, ReadInput)
ASSERT_EQ(child_map.at("bool").get_boolean(), false);
}

TEST(JsonConfig, ReadInputString)
{
std::string json_string = R"({"item": 4,
"array": [3.0, 4.5],
"map": {"bool": false}})";

auto ptree = gko::ext::config::parse_json_string(json_string);

auto& child_array = ptree.get("array").get_array();
auto& child_map = ptree.get("map").get_map();
ASSERT_EQ(ptree.get_map().size(), 3);
ASSERT_EQ(ptree.get("item").get_integer(), 4);
ASSERT_EQ(child_array.size(), 2);
ASSERT_EQ(child_array.at(0).get_real(), 3.0);
ASSERT_EQ(child_array.at(1).get_real(), 4.5);
ASSERT_EQ(child_map.size(), 1);
ASSERT_EQ(child_map.at("bool").get_boolean(), false);
}


TEST(JsonConfig, ReadInputFromFile)
{
Expand Down
7 changes: 7 additions & 0 deletions include/ginkgo/extensions/config/json_config.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,13 @@ inline gko::config::pnode parse_json_file(std::string filename)
return parse_json(nlohmann::json::parse(fstream));
}

/**
* parse_json_string takes a json string to generate the property tree object
*/
inline gko::config::pnode parse_json_string(std::string json)
{
return parse_json(nlohmann::json::parse(json));
}

} // namespace config
} // namespace ext
Expand Down

0 comments on commit 3d30c04

Please sign in to comment.