ClickHouse/src/Common/JSONBuilder.cpp

100 lines
2.3 KiB
C++
Raw Normal View History

2021-04-13 17:31:43 +00:00
#include <Common/JSONBuilder.h>
#include <IO/WriteHelpers.h>
#include <Common/typeid_cast.h>
2021-04-13 17:31:43 +00:00
namespace DB::JSONBuilder
{
static bool isArrayOrMap(const IItem & item)
{
return typeid_cast<const JSONArray *>(&item) || typeid_cast<const JSONMap *>(&item);
}
static bool isSimpleArray(const std::vector<ItemPtr> & values)
{
for (const auto & value : values)
if (isArrayOrMap(*value))
return false;
return true;
}
2021-04-13 17:31:43 +00:00
void JSONString::format(const FormatSettings & settings, FormatContext & context)
{
writeJSONString(value, context.out, settings.settings);
}
void JSONBool::format(const FormatSettings &, FormatContext & context)
{
writeString(value ? "true" : "false", context.out);
}
2021-04-13 17:31:43 +00:00
void JSONArray::format(const FormatSettings & settings, FormatContext & context)
{
writeChar('[', context.out);
2021-04-13 17:31:43 +00:00
context.offset += settings.indent;
bool single_row = settings.print_simple_arrays_in_single_row && isSimpleArray(values);
2021-04-13 17:31:43 +00:00
bool first = true;
for (const auto & value : values)
{
if (!first)
writeChar(',', context.out);
2021-04-13 17:31:43 +00:00
if (!single_row)
{
writeChar('\n', context.out);
writeChar(' ', context.offset, context.out);
}
else if (!first)
writeChar(' ', context.out);
2021-04-13 17:31:43 +00:00
first = false;
2021-04-13 17:31:43 +00:00
value->format(settings, context);
}
context.offset -= settings.indent;
if (!single_row)
{
writeChar('\n', context.out);
writeChar(' ', context.offset, context.out);
}
writeChar(']', context.out);
2021-04-13 17:31:43 +00:00
}
void JSONMap::format(const FormatSettings & settings, FormatContext & context)
{
writeChar('{', context.out);
2021-04-13 17:31:43 +00:00
context.offset += settings.indent;
bool first = true;
for (const auto & value : values)
{
if (!first)
writeChar(',', context.out);
2021-04-13 17:31:43 +00:00
first = false;
writeChar('\n', context.out);
writeChar(' ', context.offset, context.out);
2021-04-13 17:31:43 +00:00
writeJSONString(value.key, context.out, settings.settings);
writeChar(':', context.out);
writeChar(' ', context.out);
2021-04-13 17:31:43 +00:00
value.value->format(settings, context);
}
context.offset -= settings.indent;
writeChar('\n', context.out);
writeChar(' ', context.offset, context.out);
writeChar('}', context.out);
2021-04-13 17:31:43 +00:00
}
}