CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/Common/Data/Format/JSONWriter.h
Views: 1401
// Minimal-state JSON writer. Consumes almost no memory1// apart from the string being built-up, which could easily be replaced2// with a file stream (although I've chosen not to do that just yet).3//4// Writes nicely 2-space indented output with correct comma-placement5// in arrays and dictionaries.6//7// Does not deal with encodings in any way.8//9// Zero dependencies apart from stdlib (if you remove the vhjson usage.)1011#pragma once1213#include <string>14#include <vector>15#include <sstream>1617struct JsonNode;1819namespace json {2021class JsonWriter {22public:23JsonWriter(int flags = NORMAL);24~JsonWriter();25void begin();26void beginArray();27void beginRaw();28void end();29void pushDict();30void pushDict(const std::string &name);31void pushArray();32void pushArray(const std::string &name);33void pop();34void writeBool(bool value);35void writeBool(const std::string &name, bool value);36void writeInt(int value);37void writeInt(const std::string &name, int value);38void writeUint(uint32_t value);39void writeUint(const std::string &name, uint32_t value);40void writeFloat(double value);41void writeFloat(const std::string &name, double value);42void writeString(const std::string &value);43void writeString(const std::string &name, const std::string &value);44void writeRaw(const std::string &value);45void writeRaw(const std::string &name, const std::string &value);46void writeNull();47void writeNull(const std::string &name);4849std::string str() const {50return str_.str();51}5253std::string flush() {54std::string result = str_.str();55str_.str("");56return result;57}5859enum {60NORMAL = 0,61PRETTY = 1,62};6364private:65const char *indent(int n) const;66const char *comma() const;67const char *arrayComma() const;68const char *indent() const;69const char *arrayIndent() const;70void writeEscapedString(const std::string &s);7172enum BlockType {73ARRAY,74DICT,75RAW,76};77struct StackEntry {78StackEntry(BlockType t) : type(t), first(true) {}79BlockType type;80bool first;81};82std::vector<StackEntry> stack_;83std::ostringstream str_;84bool pretty_;85};8687std::string json_stringify(const JsonNode *json);8889} // namespace json909192