-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson_dumper.hpp
47 lines (34 loc) · 1.03 KB
/
json_dumper.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#pragma once
#include <iostream>
#include <string>
#include <utility>
#include <vector>
class JsonDumper {
struct KeyValue {
std::string key;
std::string value;
};
std::vector<KeyValue> _items;
bool dump_at_end = false;
public:
JsonDumper(bool dump_at_end_ = false) : dump_at_end(dump_at_end_) {}
~JsonDumper() {
if (dump_at_end) std::cout << dump() << std::endl;
}
void set_dump_at_end() { dump_at_end = true; }
void operator()(const std::string &key, const std::string &value) {
_items.push_back(KeyValue{key, "\"" + value + "\""});
}
template <class T> void operator()(const std::string &key, T value) {
_items.push_back(KeyValue{key, std::to_string(value)});
}
std::string dump() const {
std::string ret = "{\n";
if (!_items.empty()) {
for (const auto &[k, v] : _items) ret += " \"" + k + "\": " + v + ",\n";
ret.erase(ret.end() - 2);
}
ret += "}";
return ret;
}
} jdump;