2#include "nlohmann/json.hpp"
3#include <nlohmann/json-schema.hpp>
13using nlohmann::json_schema::json_validator;
19 if (!std::filesystem::is_regular_file(path)) {
20 throw std::invalid_argument(
"Path to be loaded does not exist: " + path);
22 auto stream = std::ifstream(path);
24 throw std::invalid_argument(
"File stream cannot be opened from: " + path);
27 return nlohmann::json::parse(stream);
30 throw std::invalid_argument(
"File at " + path +
" is not valid JSON");
34 inline auto all_same_length(
const nlohmann::json& j,
const std::vector<std::string>& ks) {
35 std::set<
decltype(j[0].size())> lengths;
36 for (
auto k : ks) { lengths.insert(j.at(k).size()); }
37 return lengths.size() == 1;
41 if (j.is_null() || (j.is_array() && j.size() == 0)){
42 return Eigen::ArrayXXd(0, 0);
45 const std::valarray<std::valarray<double>> m = j;
47 Eigen::ArrayXXd mat(m.size(), m.size());
52 for (
auto i = 0U; i < m.size(); ++i){
54 if (row.size() !=
static_cast<std::size_t
>(mat.rows())){
55 throw std::invalid_argument(
"provided matrix is not square");
57 for (
auto k = 0U; k < row.size(); ++k){
63 catch(
const nlohmann::json::exception&){
79 auto is_valid_path = [](
const std::string & s){
81 return std::filesystem::is_regular_file(s) ||
true;
89 if (j.is_null() || (j.is_array() && j.empty()) || (j.is_string() && j.get<std::string>().empty())){
92 else if (j.is_object()){
96 else if (j.is_array() && j.size() > 0){
99 else if (j.is_string()){
101 std::string s = j.get<std::string>();
104 if (is_valid_path(s) && std::filesystem::is_regular_file(s)){
109 return nlohmann::json::parse(s);
135 class custom_error_handler :
public nlohmann::json_schema::basic_error_handler
138 std::vector<std::string> errors;
139 void error(
const nlohmann::json::json_pointer &ptr,
const json &instance,
const std::string &message)
override
141 nlohmann::json_schema::basic_error_handler::error(ptr, instance, message);
142 std::stringstream ss;
143 ss << ptr <<
":" << instance <<
"': " << message <<
"\n";
144 errors.push_back(ss.str());
148 return handler.errors;
JSONValidator(const nlohmann::json &schema)
bool is_valid(const nlohmann::json &j) const
const nlohmann::json schema
std::vector< std::string > get_validation_errors(const nlohmann::json &j) const
nlohmann::json load_a_JSON_file(const std::string &path)
Load a JSON file from a specified file.
auto all_same_length(const nlohmann::json &j, const std::vector< std::string > &ks)
auto multilevel_JSON_load(const nlohmann::json &j, const std::string &default_path)