-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson.hpp
More file actions
603 lines (525 loc) · 16.3 KB
/
json.hpp
File metadata and controls
603 lines (525 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
// LightJSON - Simple, Light Weight, Header Only, C++11 compliant JSON Library.
// Github: https://github.com/rft0/lightjson
// For those who do not want to include json library heavier than small codebase itself.
// Define JSON_DISABLE_DUMPING to not generate JSON::dump() and related methods if you don't need it.
// This will help to reduce size of the compiled binary.
#ifndef __JSON_HPP__
#define __JSON_HPP__
#include <string>
#include <vector>
#include <map>
#include <cstring>
#include <stdexcept>
#include <fstream>
#include <sstream>
#include <cctype>
#include <iomanip>
#include <type_traits>
// #define JSON_DISABLE_DUMPING
template<typename T, typename Enable = void>
struct JSONTypeTraits;
class JSON {
public:
enum Type {
Null,
Boolean,
Integer,
Double,
String,
Array,
Object
};
static JSON o(std::initializer_list<std::pair<std::string, JSON>> list) {
std::map<std::string, JSON> obj;
for (const auto& pair : list) {
obj[pair.first] = pair.second;
}
return JSON(obj);
}
JSON() : type(Null) {}
JSON(bool b) : type(Boolean), boolean(b) {}
JSON(int i) : type(Integer), integer(i) {}
JSON(double d) : type(Double), doubleVal(d) {}
JSON(const char* s) : type(String), string(new std::string(s)) {}
JSON(const std::string& s) : type(String), string(new std::string(s)) {}
JSON(const std::vector<JSON>& a) : type(Array), array(new std::vector<JSON>(a)) {}
JSON(std::initializer_list<JSON> list) : type(Array), array(new std::vector<JSON>(list)) {}
JSON(const std::map<std::string, JSON>& obj) : type(Object), object(new std::map<std::string, JSON>(obj)) {}
~JSON() {
clear();
}
JSON(const JSON& other) : type(other.type) {
copy(other);
}
template<typename T>
T as() const {
return JSONTypeTraits<T>::as(*this);
}
#ifndef JSON_DISABLE_DUMPING
friend std::ostream& operator<<(std::ostream &os, const JSON &json) {
os << json.dump();
return os;
}
#endif
JSON& operator=(const JSON& other) {
if (this != &other) {
clear();
type = other.type;
copy(other);
}
return *this;
}
JSON& operator=(bool b) {
clear();
type = Boolean;
boolean = b;
return *this;
}
JSON& operator=(int i) {
clear();
type = Integer;
integer = i;
return *this;
}
JSON& operator=(double d) {
clear();
type = Double;
doubleVal = d;
return *this;
}
JSON& operator=(const char* s) {
clear();
type = String;
string = new std::string(s);
return *this;
}
JSON& operator=(const std::string& s) {
clear();
type = String;
string = new std::string(s);
return *this;
}
JSON& operator=(const std::vector<JSON>& a) {
clear();
type = Array;
array = new std::vector<JSON>(a);
return *this;
}
JSON& operator=(const std::map<std::string, JSON>& obj) {
clear();
type = Object;
object = new std::map<std::string, JSON>(obj);
return *this;
}
JSON& operator=(std::initializer_list<JSON> list) {
clear();
type = Array;
array = new std::vector<JSON>(list);
return *this;
}
JSON& operator[](const std::string& key) {
if (type != Object) {
if (type == Null) {
type = Object;
object = new std::map<std::string, JSON>();
} else {
std::ostringstream oss;
oss << "Field \"" << key << "\" is not an object.";
throw std::runtime_error(oss.str());
}
}
return (*object)[key];
}
const JSON& operator[](const std::string& key) const {
if (type != Object) {
std::ostringstream oss;
oss << "Field \"" << key << "\" is not an object.";
throw std::runtime_error(oss.str());
}
return object->at(key);
}
JSON& operator[](size_t index) {
if (type != Array)
throw std::runtime_error("Trying to index a non-array JSON");
if (index >= array->size())
throw std::runtime_error("Index out of range");
return (*array)[index];
}
const JSON& operator[](size_t index) const {
if (type != Array)
throw std::runtime_error("Trying to index a non-array JSON");
if (index >= array->size())
throw std::runtime_error("Index out of range");
return (*array)[index];
}
std::vector<JSON>::iterator begin() {
if (type != Array)
throw std::runtime_error("Value is not an array.");
return array->begin();
}
std::vector<JSON>::iterator end() {
if (type != Array)
throw std::runtime_error("Value is not an array.");
return array->end();
}
std::vector<JSON>::const_iterator begin() const {
if (type != Array)
throw std::runtime_error("JSON is not an array.");
return array->begin();
}
std::vector<JSON>::const_iterator end() const {
if (type != Array)
throw std::runtime_error("JSON is not an array.");
return array->end();
}
#ifndef JSON_DISABLE_DUMPING
std::string dump(int indent = 4) const {
std::ostringstream oss;
dumpValue(*this, oss, 0, indent);
return oss.str();
}
#endif
private:
template<typename T, typename Enable>
friend struct JSONTypeTraits;
Type type;
union {
bool boolean;
int integer;
double doubleVal;
std::string* string;
std::vector<JSON>* array;
std::map<std::string, JSON>* object;
};
void clear() {
switch (type) {
case String: delete string; break;
case Array: delete array; break;
case Object: delete object; break;
default: break;
}
type = Null;
}
void copy(const JSON& other) {
switch (other.type) {
case Boolean: boolean = other.boolean; break;
case Integer: integer = other.integer; break;
case Double: doubleVal = other.doubleVal; break;
case String: string = new std::string(*other.string); break;
case Array: array = new std::vector<JSON>(*other.array); break;
case Object: object = new std::map<std::string, JSON>(*other.object); break;
default: break;
}
}
#ifndef JSON_DISABLE_DUMPING
void dumpValue(const JSON& value, std::ostringstream& oss, int level, int indent) const {
switch (value.type) {
case Null: oss << "null"; break;
case Boolean: oss << (value.boolean ? "true" : "false"); break;
case Integer: oss << value.integer; break;
case Double: oss << value.doubleVal; break;
case String: dumpString(*value.string, oss); break;
case Array: dumpArray(*value.array, oss, level, indent); break;
case Object: dumpObject(*value.object, oss, level, indent); break;
}
}
void dumpString(const std::string& str, std::ostringstream& oss) const {
oss << '"';
for (char ch : str) {
switch (ch) {
case '"': oss << "\\\""; break;
case '\\': oss << "\\\\"; break;
case '\b': oss << "\\b"; break;
case '\f': oss << "\\f"; break;
case '\n': oss << "\\n"; break;
case '\r': oss << "\\r"; break;
case '\t': oss << "\\t"; break;
default:
if (ch < 32 || ch == 127) {
oss << "\\u" << std::hex << std::setw(4) << std::setfill('0') << static_cast<int>(ch);
} else {
oss << ch;
}
break;
}
}
oss << '"';
}
void dumpArray(const std::vector<JSON>& arr, std::ostringstream& oss, int level, int indent) const {
bool hasComplexChildren = false;
for (const auto& item : arr) {
if (item.type == JSON::Object || item.type == JSON::Array) {
hasComplexChildren = true;
break;
}
}
const bool prettyPrint = hasComplexChildren && (indent > 0);
oss << '[';
if (prettyPrint)
oss << '\n';
for (size_t i = 0; i < arr.size(); ++i) {
if (prettyPrint) {
oss << std::string(level + indent, ' ');
}
dumpValue(arr[i], oss, level + indent, indent);
if (i < arr.size() - 1) {
oss << ',';
if (!prettyPrint) oss << ' ';
}
if (prettyPrint)
oss << '\n';
}
if (prettyPrint)
oss << std::string(level, ' ');
oss << ']';
}
void dumpObject(const std::map<std::string, JSON>& obj, std::ostringstream& oss, int level, int indent) const {
oss << '{';
if (indent > 0) oss << '\n';
size_t i = 0;
for (const auto& pair : obj) {
const std::string& key = pair.first;
const JSON& value = pair.second;
if (indent > 0) oss << std::string(level + indent, ' ');
dumpString(key, oss);
oss << ':';
if (indent > 0) oss << ' ';
dumpValue(value, oss, level + indent, indent);
if (++i < obj.size()) oss << ',';
if (indent > 0) oss << '\n';
}
if (indent > 0) oss << std::string(level, ' ');
oss << '}';
}
#endif
};
template<>
struct JSONTypeTraits<bool> {
static bool as(const JSON& json) {
if (json.type != JSON::Boolean)
throw std::runtime_error("Not a boolean");
return json.boolean;
}
};
template<>
struct JSONTypeTraits<int> {
static int as(const JSON& json) {
if (json.type != JSON::Integer)
throw std::runtime_error("Not an integer");
return json.integer;
}
};
template<>
struct JSONTypeTraits<double> {
static double as(const JSON& json) {
if (json.type != JSON::Double)
throw std::runtime_error("Not a double");
return json.doubleVal;
}
};
template<>
struct JSONTypeTraits<std::string> {
static std::string as(const JSON& json) {
if (json.type != JSON::String)
throw std::runtime_error("Not a string");
return *json.string;
}
};
template<typename T>
struct JSONTypeTraits<std::vector<T>> {
static std::vector<T> as(const JSON& json) {
if (json.type != JSON::Array)
throw std::runtime_error("Not an array");
std::vector<T> result;
const auto& arr = *json.array;
for (const auto& item : arr) {
result.push_back(item.as<T>());
}
return result;
}
};
template<>
struct JSONTypeTraits<std::map<std::string, JSON>> {
static std::map<std::string, JSON> as(const JSON& json) {
if (json.type != JSON::Object)
throw std::runtime_error("Not an object");
return *json.object;
}
};
template<typename T>
struct JSONTypeTraits<T, typename std::enable_if<std::is_arithmetic<T>::value>::type> {
static T as(const JSON& json) {
switch (json.type) {
case JSON::Integer: return static_cast<T>(json.integer);
case JSON::Double: return static_cast<T>(json.doubleVal);
default: throw std::runtime_error("Not a numeric type");
}
}
};
class JSONParser {
public:
JSONParser(const std::string& data) : data(data), pos(0), line(1), col(1) {}
JSONParser(std::ifstream& f)
: data(std::string((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>())), pos(0), line(1), col(1) {}
static JSON parse(const std::string& data) {
JSONParser parser(data);
if (parser.data.empty())
throw std::runtime_error("Empty JSON file");
return parser.parse();
}
static JSON parse(std::ifstream& f) {
JSONParser parser(f);
if (parser.data.empty())
throw std::runtime_error("Empty JSON file");
return parser.parse();
}
private:
std::string data;
int pos;
int line;
int col;
JSON parse() {
skipWhitespace();
return parseValue();
}
void advance(int count = 1) {
for (int i = 0; i < count; ++i) {
if (data[pos] == '\n') {
line++;
col = 1;
} else {
col++;
}
pos++;
}
}
void skipWhitespace() {
while (data[pos] && isspace(data[pos])) {
advance();
}
}
[[noreturn]] void throwError(const std::string& message) const {
std::ostringstream oss;
oss << message << " at line " << line << ", column " << col;
throw std::runtime_error(oss.str());
}
JSON parseValue() {
skipWhitespace();
char ch = data[pos];
if (ch == '{')
return parseObject();
else if (ch == '[')
return parseArray();
else if (ch == '"')
return parseString();
else if (ch == 't' || ch == 'f')
return parseBoolean();
else if (ch == 'n')
return parseNull();
else if (ch == '-' || (ch >= '0' && ch <= '9'))
return parseNumber();
else
throwError("Unexpected character in JSON");
}
JSON parseObject() {
advance();
std::map<std::string, JSON> obj;
skipWhitespace();
while (data[pos] != '}') {
std::string key = parseString().as<std::string>();
skipWhitespace();
if (data[pos] != ':') {
throwError("Expected ':' in JSON object");
}
advance();
JSON value = parseValue();
obj[key] = value;
skipWhitespace();
if (data[pos] == ',') {
advance();
skipWhitespace();
}
}
advance();
return JSON(obj);
}
JSON parseArray() {
advance();
std::vector<JSON> arr;
skipWhitespace();
while (data[pos] != ']') {
arr.push_back(parseValue());
skipWhitespace();
if (data[pos] == ',') {
advance();
skipWhitespace();
}
}
advance();
return JSON(arr);
}
JSON parseString() {
advance();
std::string str;
while (data[pos] != '"') {
if (data[pos] == '\\') {
advance();
switch (data[pos]) {
case '\\': str += '\\'; break;
case '"': str += '"'; break;
case '/': str += '/'; break;
case 'b': str += '\b'; break;
case 'f': str += '\f'; break;
case 'n': str += '\n'; break;
case 'r': str += '\r'; break;
case 't': str += '\t'; break;
default: throwError("Invalid escape character in string");
}
advance();
} else {
str += data[pos];
advance();
}
}
advance();
return JSON(str);
}
JSON parseBoolean() {
if (strncmp(&data[pos], "true", 4) == 0) {
advance(4);
return JSON(true);
} else if (strncmp(&data[pos], "false", 5) == 0) {
advance(5);
return JSON(false);
} else {
throwError("Unexpected boolean value in JSON");
}
}
JSON parseNull() {
if (strncmp(&data[pos], "null", 4) == 0) {
advance(4);
return JSON();
} else {
throwError("Unexpected null value in JSON");
}
}
JSON parseNumber() {
size_t start = pos;
if (data[pos] == '-') {
advance();
}
while (data[pos] >= '0' && data[pos] <= '9') {
advance();
}
if (data[pos] == '.') {
advance();
while (data[pos] >= '0' && data[pos] <= '9') {
advance();
}
return JSON(std::stod(std::string(&data[start], pos - start)));
} else {
return JSON(std::stoi(std::string(&data[start], pos - start)));
}
}
};
#endif