Stochastic Loading Module
json_object.cc
1 #include <fstream>
2 #include <iomanip>
3 #include <iostream>
4 #include <stdexcept>
5 #include <string>
6 // JSON for Modern C++ single-include header
7 #include <nlohmann_json/json.hpp>
8 #include "json_object.h"
9 
11  // This is constructed here to ensure the JSON member is stored as an object
12  json_object_ = json::object();
13 }
14 
17 {
18  json_object_ = library_json;
19 }
20 
21 bool utilities::JsonObject::delete_key(const std::string& key) {
22  bool status = true;
23 
24  int erased = json_object_.erase(key);
25 
26  if (erased != 1) {
27  status = false;
28  throw std::runtime_error(
29  "\nWARNING: In utilities::JsonObject::delete_key: Key not present, so "
30  "no values were erased\n");
31  }
32 
33  return status;
34 }
35 
37  const std::string& output_location) const {
38  bool status = true;
39  std::ofstream output_file;
40  output_file.open(output_location);
41 
42  if (!output_file.is_open()) {
43  status = false;
44  throw std::runtime_error(
45  "\nERROR: In utilities::JsonObject::write_to_file(): Could not open "
46  "output location\n");
47  }
48 
49  // Write prettyfied JSON to file
50  output_file << std::setw(4) << json_object_ << std::endl;
51 
52  output_file.close();
53 
54  if (output_file.fail()) {
55  status = false;
56  throw std::runtime_error(
57  "\nERROR: In utilities::JsonObject::write_to_file(): Error when "
58  "closing output location\n");
59  }
60 
61  return status;
62 }
63 
65  json_object_.clear();
66 }
67 
69  return json_object_.empty();
70 }
71 
72 unsigned int utilities::JsonObject::get_size() const {
73  return json_object_.size();
74 }
bool write_to_file(const std::string &output_location) const
Definition: json_object.cc:36
bool delete_key(const std::string &key)
Definition: json_object.cc:21
unsigned int get_size() const
Definition: json_object.cc:72
bool is_empty() const
Definition: json_object.cc:68