1#include "JSONString.h"
2
3#include <regex>
4#include <sstream>
5namespace DB
6{
7
8namespace
9{
10std::string pad(size_t padding)
11{
12 return std::string(padding * 4, ' ');
13}
14
15const std::regex NEW_LINE{"\n"};
16}
17
18void JSONString::set(const std::string & key, std::string value, bool wrap)
19{
20 if (value.empty())
21 value = "null";
22
23 bool reserved = (value[0] == '[' || value[0] == '{' || value == "null");
24 if (!reserved && wrap)
25 value = '"' + std::regex_replace(value, NEW_LINE, "\\n") + '"';
26
27 content[key] = value;
28}
29
30void JSONString::set(const std::string & key, const std::vector<JSONString> & run_infos)
31{
32 std::ostringstream value;
33 value << "[\n";
34
35 for (size_t i = 0; i < run_infos.size(); ++i)
36 {
37 value << pad(padding + 1) + run_infos[i].asString(padding + 2);
38 if (i != run_infos.size() - 1)
39 value << ',';
40
41 value << "\n";
42 }
43
44 value << pad(padding) << ']';
45 content[key] = value.str();
46}
47
48std::string JSONString::asString(size_t cur_padding) const
49{
50 std::ostringstream repr;
51 repr << "{";
52
53 for (auto it = content.begin(); it != content.end(); ++it)
54 {
55 if (it != content.begin())
56 repr << ',';
57 /// construct "key": "value" string with padding
58 repr << "\n" << pad(cur_padding) << '"' << it->first << '"' << ": " << it->second;
59 }
60
61 repr << "\n" << pad(cur_padding - 1) << '}';
62 return repr.str();
63}
64
65
66}
67