OrangePi3588Media/include/utils/simple_json_writer.h
2025-12-31 11:00:08 +08:00

81 lines
2.1 KiB
C++

#pragma once
#include <sstream>
#include <string>
#include <string_view>
#include "utils/simple_json.h"
namespace rk3588 {
inline std::string JsonEscapeString(std::string_view s) {
std::string out;
out.reserve(s.size() + 8);
for (char c : s) {
switch (c) {
case '\\': out += "\\\\"; break;
case '"': out += "\\\""; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (static_cast<unsigned char>(c) < 0x20) {
out += "?";
} else {
out.push_back(c);
}
}
}
return out;
}
inline void StringifySimpleJsonTo(const SimpleJson& v, std::ostringstream& oss);
inline void StringifyArrayTo(const SimpleJson::Array& arr, std::ostringstream& oss) {
oss << '[';
for (size_t i = 0; i < arr.size(); ++i) {
if (i) oss << ',';
StringifySimpleJsonTo(arr[i], oss);
}
oss << ']';
}
inline void StringifyObjectTo(const SimpleJson::Object& obj, std::ostringstream& oss) {
oss << '{';
bool first = true;
for (const auto& kv : obj) {
if (!first) oss << ',';
first = false;
oss << '"' << JsonEscapeString(kv.first) << '"' << ':';
StringifySimpleJsonTo(kv.second, oss);
}
oss << '}';
}
inline void StringifySimpleJsonTo(const SimpleJson& v, std::ostringstream& oss) {
if (v.IsNull()) {
oss << "null";
} else if (v.IsBool()) {
oss << (v.AsBool(false) ? "true" : "false");
} else if (v.IsNumber()) {
// Keep simple.
oss << v.AsNumber(0.0);
} else if (v.IsString()) {
oss << '"' << JsonEscapeString(v.AsString("")) << '"';
} else if (v.IsArray()) {
StringifyArrayTo(v.AsArray(), oss);
} else if (v.IsObject()) {
StringifyObjectTo(v.AsObject(), oss);
} else {
oss << "null";
}
}
inline std::string StringifySimpleJson(const SimpleJson& v) {
std::ostringstream oss;
StringifySimpleJsonTo(v, oss);
return oss.str();
}
} // namespace rk3588