ClickHouse/dbms/programs/performance-test/JSONString.cpp

67 lines
1.4 KiB
C++
Raw Normal View History

2019-01-25 11:03:02 +00:00
#include "JSONString.h"
#include <regex>
#include <sstream>
2019-01-25 11:03:02 +00:00
namespace DB
{
namespace
{
std::string pad(size_t padding)
2019-01-25 11:03:02 +00:00
{
return std::string(padding * 4, ' ');
2019-01-25 11:03:02 +00:00
}
const std::regex NEW_LINE{"\n"};
}
void JSONString::set(const std::string & key, std::string value, bool wrap)
2019-01-25 11:03:02 +00:00
{
if (value.empty())
value = "null";
bool reserved = (value[0] == '[' || value[0] == '{' || value == "null");
if (!reserved && wrap)
value = '"' + std::regex_replace(value, NEW_LINE, "\\n") + '"';
content[key] = value;
}
void JSONString::set(const std::string & key, const std::vector<JSONString> & run_infos)
2019-01-25 11:03:02 +00:00
{
std::ostringstream value;
value << "[\n";
2019-01-25 11:03:02 +00:00
for (size_t i = 0; i < run_infos.size(); ++i)
{
value << pad(padding + 1) + run_infos[i].asString(padding + 2);
2019-01-25 11:03:02 +00:00
if (i != run_infos.size() - 1)
value << ',';
2019-01-25 11:03:02 +00:00
value << "\n";
2019-01-25 11:03:02 +00:00
}
value << pad(padding) << ']';
content[key] = value.str();
2019-01-25 11:03:02 +00:00
}
std::string JSONString::asString(size_t cur_padding) const
2019-01-25 11:03:02 +00:00
{
std::ostringstream repr;
repr << "{";
2019-01-25 11:03:02 +00:00
for (auto it = content.begin(); it != content.end(); ++it)
{
if (it != content.begin())
repr << ',';
2019-01-25 11:03:02 +00:00
/// construct "key": "value" string with padding
repr << "\n" << pad(cur_padding) << '"' << it->first << '"' << ": " << it->second;
2019-01-25 11:03:02 +00:00
}
repr << "\n" << pad(cur_padding - 1) << '}';
return repr.str();
2019-01-25 11:03:02 +00:00
}
}