CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hrydgard

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: hrydgard/ppsspp
Path: blob/master/Common/Data/Format/JSONWriter.h
Views: 1401
1
// Minimal-state JSON writer. Consumes almost no memory
2
// apart from the string being built-up, which could easily be replaced
3
// with a file stream (although I've chosen not to do that just yet).
4
//
5
// Writes nicely 2-space indented output with correct comma-placement
6
// in arrays and dictionaries.
7
//
8
// Does not deal with encodings in any way.
9
//
10
// Zero dependencies apart from stdlib (if you remove the vhjson usage.)
11
12
#pragma once
13
14
#include <string>
15
#include <vector>
16
#include <sstream>
17
18
struct JsonNode;
19
20
namespace json {
21
22
class JsonWriter {
23
public:
24
JsonWriter(int flags = NORMAL);
25
~JsonWriter();
26
void begin();
27
void beginArray();
28
void beginRaw();
29
void end();
30
void pushDict();
31
void pushDict(const std::string &name);
32
void pushArray();
33
void pushArray(const std::string &name);
34
void pop();
35
void writeBool(bool value);
36
void writeBool(const std::string &name, bool value);
37
void writeInt(int value);
38
void writeInt(const std::string &name, int value);
39
void writeUint(uint32_t value);
40
void writeUint(const std::string &name, uint32_t value);
41
void writeFloat(double value);
42
void writeFloat(const std::string &name, double value);
43
void writeString(const std::string &value);
44
void writeString(const std::string &name, const std::string &value);
45
void writeRaw(const std::string &value);
46
void writeRaw(const std::string &name, const std::string &value);
47
void writeNull();
48
void writeNull(const std::string &name);
49
50
std::string str() const {
51
return str_.str();
52
}
53
54
std::string flush() {
55
std::string result = str_.str();
56
str_.str("");
57
return result;
58
}
59
60
enum {
61
NORMAL = 0,
62
PRETTY = 1,
63
};
64
65
private:
66
const char *indent(int n) const;
67
const char *comma() const;
68
const char *arrayComma() const;
69
const char *indent() const;
70
const char *arrayIndent() const;
71
void writeEscapedString(const std::string &s);
72
73
enum BlockType {
74
ARRAY,
75
DICT,
76
RAW,
77
};
78
struct StackEntry {
79
StackEntry(BlockType t) : type(t), first(true) {}
80
BlockType type;
81
bool first;
82
};
83
std::vector<StackEntry> stack_;
84
std::ostringstream str_;
85
bool pretty_;
86
};
87
88
std::string json_stringify(const JsonNode *json);
89
90
} // namespace json
91
92