bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
json_file_reader.h
Go to the documentation of this file.
1#ifndef BITSIM_UTILS_IO_JSON_FILE_READER_H
2#define BITSIM_UTILS_IO_JSON_FILE_READER_H
3
4#include "bitsim/extern/nlohmann/json/json.hpp"
6#include <filesystem>
7
8namespace bitsim
9{
10namespace utils::io
11{
15class JSONFileReader final : public FileReaderBase
16{
17
18 public:
19 using json = nlohmann::json;
20
25 JSONFileReader(const std::string &filename);
26
29 JSONFileReader(const std::filesystem::path &filename);
30
34 virtual void open() override final;
35
39 template <typename T> T get_value(const std::string &label) const;
40
48 template <typename T> T at(const std::string &label) const;
49
55 const json &get(const std::string &label) const { return data_.at(label); };
56
57 private:
58 json data_;
59};
60
61template <typename T> T JSONFileReader::get_value(const std::string &label) const
62{
63 if (!this->is_open())
64 {
65 throw std::logic_error("JSON file is not open. Have you called open()?");
66 }
67 return data_[label].template get<T>();
68}
69
70template <typename T> T JSONFileReader::at(const std::string &label) const
71{
72 if (!this->is_open())
73 {
74 throw std::logic_error("JSON file is not open. Have you called open()?");
75 }
76
77 auto data = data_.at(label);
78 return T(data);
79}
80
81} // namespace utils::io
82} // namespace bitsim
83#endif // BITSIM_UTILS_IO_JSON_FILE_READER_H
bool is_open() const noexcept
Definition file_handler_base.h:113
FileReaderBase(const std::string &file_name, FileFormats::Type t)
Constructor.
Definition file_reader_base.cpp:15
nlohmann::json json
Definition json_file_reader.h:19
JSONFileReader(const std::string &filename)
Definition json_file_reader.cpp:9
const json & get(const std::string &label) const
Definition json_file_reader.h:55
virtual void open() override final
Attempts to open the file for reading.
Definition json_file_reader.cpp:19
T get_value(const std::string &label) const
Get the value specified by the label.
Definition json_file_reader.h:61
T at(const std::string &label) const
Definition json_file_reader.h:70
Definition csv_file_reader.cpp:12
Definition dc_motor_backend_base.h:9