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
|
// *****************************************************************************
// * This file is part of the FreeFileSync project. It is distributed under *
// * GNU General Public License: https://www.gnu.org/licenses/gpl-3.0 *
// * Copyright (C) Zenju (zenju AT freefilesync DOT org) - All Rights Reserved *
// *****************************************************************************
#ifndef JSON_H_0187348321748321758934215734
#define JSON_H_0187348321748321758934215734
#include <zen/string_tools.h>
namespace zen
{
//Spec: https://tools.ietf.org/html/rfc8259
//Test: http://seriot.ch/parsing_json.php
struct JsonValue
{
enum class Type
{
null, //
boolean, //primitive types
number, //
string, //
array,
object,
};
/**/ JsonValue() {}
explicit JsonValue(Type t) : type(t) {}
explicit JsonValue(bool b) : type(Type::boolean), primVal(b ? "true" : "false") {}
explicit JsonValue(int num) : type(Type::number), primVal(numberTo<std::string>(num)) {}
explicit JsonValue(int64_t num) : type(Type::number), primVal(numberTo<std::string>(num)) {}
explicit JsonValue(double num) : type(Type::number), primVal(numberTo<std::string>(num)) {}
explicit JsonValue(std::string str) : type(Type::string), primVal(std::move(str)) {} //unifying assignment
explicit JsonValue(const char* str) : type(Type::string), primVal(str) {}
explicit JsonValue(const void*) = delete; //catch usage errors e.g. const int* -> JsonValue(bool)
//explicit JsonValue(std::initializer_list<JsonValue> initList) : type(Type::array), arrayVal(initList) {} => empty list is ambiguous
explicit JsonValue(std::vector<JsonValue> initList) : type(Type::array), arrayVal(std::move(initList)) {} //unifying assignment
Type type = Type::null;
std::string primVal; //for primitive types
std::vector<JsonValue> arrayVal;
std::map<std::string, JsonValue> objectVal; //"[...] most implementations of JSON libraries do not accept duplicate keys [...]" => fine!
//alternative: std::unordered_map => but let's keep std::map, so that objectVal is sorted for our unit tests
};
std::string serializeJson(const JsonValue& jval,
const std::string& lineBreak = "\n",
const std::string& indent = " "); //noexcept
struct JsonParsingError
{
JsonParsingError(size_t rowNo, size_t colNo) : row(rowNo), col(colNo) {}
const size_t row; //beginning with 0
const size_t col; //
};
JsonValue parseJson(const std::string& stream); //throw JsonParsingError
//helper functions for JsonValue access:
inline
const JsonValue* getChildFromJsonObject(const JsonValue& jvalue, const std::string& name)
{
if (jvalue.type != JsonValue::Type::object)
return nullptr;
auto it = jvalue.objectVal.find(name);
if (it == jvalue.objectVal.end())
return nullptr;
return &it->second;
}
inline
std::optional<std::string> getPrimitiveFromJsonObject(const JsonValue& jvalue, const std::string& name)
{
if (const JsonValue* childValue = getChildFromJsonObject(jvalue, name))
if (childValue->type != JsonValue::Type::object &&
childValue->type != JsonValue::Type::array)
return childValue->primVal;
return std::nullopt;
}
//---------------------- implementation ----------------------
namespace json_impl
{
namespace
{
[[nodiscard]] std::string jsonEscape(const std::string& str)
{
std::string output;
for (const char c : str)
switch (c)
{
//*INDENT-OFF*
case '\\': output += "\\\\"; break; //
case '"': output += "\\\""; break; //escaping mandatory
case '\b': output += "\\b"; break; //
case '\f': output += "\\f"; break; //
case '\n': output += "\\n"; break; //prefer compact escaping
case '\r': output += "\\r"; break; //
case '\t': output += "\\t"; break; //
default:
if (static_cast<unsigned char>(c) < 32)
{
const auto [high, low] = hexify(c);
output += "\\u00";
output += high;
output += low;
}
else
output += c;
break;
//*INDENT-ON*
}
return output;
}
[[nodiscard]] std::string jsonUnescape(const std::string& str)
{
std::string output;
std::basic_string<impl::Char16> utf16Buf;
auto flushUtf16 = [&]
{
if (!utf16Buf.empty())
{
UtfDecoder<impl::Char16> decoder(utf16Buf.c_str(), utf16Buf.size());
while (std::optional<impl::CodePoint> cp = decoder.getNext())
codePointToUtf<char>(*cp, [&](char c) { output += c; });
utf16Buf.clear();
}
};
auto writeOut = [&](char c)
{
flushUtf16();
output += c;
};
for (auto it = str.begin(); it != str.end(); ++it)
{
const char c = *it;
if (c == '\\')
{
++it;
if (it == str.end()) //unexpected end!
{
writeOut(c);
break;
}
const char c2 = *it;
switch (c2)
{
//*INDENT-OFF*
case '\\':
case '"':
case '/': writeOut(c2); break;
case 'b': writeOut('\b'); break;
case 'f': writeOut('\f'); break;
case 'n': writeOut('\n'); break;
case 'r': writeOut('\r'); break;
case 't': writeOut('\t'); break;
default:
if (c2 == 'u' &&
str.end() - it >= 5 &&
isHexDigit(it[1]) &&
isHexDigit(it[2]) &&
isHexDigit(it[3]) &&
isHexDigit(it[4]))
{
utf16Buf += static_cast<impl::Char16>(static_cast<unsigned char>(unhexify(it[1], it[2])) * 256 +
static_cast<unsigned char>(unhexify(it[3], it[4])));
it += 4;
}
else //unknown escape sequence!
{
writeOut(c);
writeOut(c2);
}
break;
//*INDENT-ON*
}
}
else
writeOut(c);
}
flushUtf16();
return output;
}
void serialize(const JsonValue& jval, std::string& stream,
const std::string& lineBreak,
const std::string& indent,
size_t indentLevel)
{
//unlike our XML serialization the caller is repsonsible for line breaks and indentation of *first* line
auto writeIndent = [&](size_t level)
{
for (size_t i = 0; i < level; ++i)
stream += indent;
};
switch (jval.type)
{
case JsonValue::Type::null:
stream += "null";
break;
case JsonValue::Type::boolean:
case JsonValue::Type::number:
stream += jval.primVal;
break;
case JsonValue::Type::string:
stream += '"' + jsonEscape(jval.primVal) + '"';
break;
case JsonValue::Type::object:
stream += '{';
if (!jval.objectVal.empty())
{
for (auto it = jval.objectVal.begin(); it != jval.objectVal.end(); ++it)
{
const auto& [childName, childValue] = *it;
if (it != jval.objectVal.begin())
stream += ',';
stream += lineBreak;
writeIndent(indentLevel + 1);
stream += '"' + jsonEscape(childName) + "\":";
if ((childValue.type == JsonValue::Type::object && !childValue.objectVal.empty()) ||
(childValue.type == JsonValue::Type::array && !childValue.arrayVal .empty()))
{
stream += lineBreak;
writeIndent(indentLevel + 1);
}
else if (!indent.empty())
stream += ' ';
serialize(childValue, stream, lineBreak, indent, indentLevel + 1);
}
stream += lineBreak;
writeIndent(indentLevel);
}
stream += '}';
break;
case JsonValue::Type::array:
stream += '[';
if (!jval.arrayVal.empty())
{
for (auto it = jval.arrayVal.begin(); it != jval.arrayVal.end(); ++it)
{
const auto& childValue = *it;
if (it != jval.arrayVal.begin())
stream += ',';
stream += lineBreak;
writeIndent(indentLevel + 1);
serialize(childValue, stream, lineBreak, indent, indentLevel + 1);
}
stream += lineBreak;
writeIndent(indentLevel);
}
stream += ']';
break;
}
}
}
}
inline
std::string serializeJson(const JsonValue& jval,
const std::string& lineBreak,
const std::string& indent) //noexcept
{
std::string output;
json_impl::serialize(jval, output, lineBreak, indent, 0);
output += lineBreak;
return output;
}
namespace json_impl
{
enum class TokenType
{
eof,
curlyOpen,
curlyClose,
squareOpen,
squareClose,
colon,
comma,
string, //
number, //primitive types
boolean, //
null, //
};
struct Token
{
Token(TokenType t) : type(t) {}
TokenType type;
std::string primVal; //for primitive types
};
class Scanner
{
public:
Scanner(const std::string& stream) : stream_(stream), pos_(stream_.begin())
{
if (zen::startsWith(stream_, BYTE_ORDER_MARK_UTF8))
pos_ += BYTE_ORDER_MARK_UTF8.size();
}
Token getNextToken() //throw JsonParsingError
{
//skip whitespace
pos_ = std::find_if_not(pos_, stream_.end(), isJsonWhiteSpace);
if (pos_ == stream_.end())
return TokenType::eof;
if (*pos_ == '{') return ++pos_, TokenType::curlyOpen;
if (*pos_ == '}') return ++pos_, TokenType::curlyClose;
if (*pos_ == '[') return ++pos_, TokenType::squareOpen;
if (*pos_ == ']') return ++pos_, TokenType::squareClose;
if (*pos_ == ':') return ++pos_, TokenType::colon;
if (*pos_ == ',') return ++pos_, TokenType::comma;
if (startsWith("null")) return pos_ += 4, Token(TokenType::null);
if (startsWith("true"))
{
pos_ += 4;
Token tk(TokenType::boolean);
tk.primVal = "true";
return tk;
}
if (startsWith("false"))
{
pos_ += 5;
Token tk(TokenType::boolean);
tk.primVal = "false";
return tk;
}
if (*pos_ == '"')
{
for (auto it = ++pos_; it != stream_.end(); ++it)
if (*it == '"')
{
Token tk(TokenType::string);
tk.primVal = jsonUnescape({pos_, it});
pos_ = ++it;
return tk;
}
else if (*it == '\\') //skip next char
if (++it == stream_.end())
break;
throw JsonParsingError(posRow(), posCol());
}
//expect a number:
const auto itNumEnd = std::find_if_not(pos_, stream_.end(), isJsonNumDigit);
if (itNumEnd == pos_)
throw JsonParsingError(posRow(), posCol());
Token tk(TokenType::number);
tk.primVal.assign(pos_, itNumEnd);
pos_ = itNumEnd;
return tk;
}
size_t posRow() const //current row beginning with 0
{
const size_t crSum = std::count(stream_.begin(), pos_, '\r'); //carriage returns
const size_t nlSum = std::count(stream_.begin(), pos_, '\n'); //new lines
assert(crSum == 0 || nlSum == 0 || crSum == nlSum);
return std::max(crSum, nlSum); //be compatible with Linux/Mac/Win
}
size_t posCol() const //current col beginning with 0
{
//seek beginning of line
for (auto it = pos_; it != stream_.begin(); )
{
--it;
if (isLineBreak(*it))
return pos_ - it - 1;
}
return pos_ - stream_.begin();
}
private:
Scanner (const Scanner&) = delete;
Scanner& operator=(const Scanner&) = delete;
static bool isJsonWhiteSpace(char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; }
static bool isJsonNumDigit (char c) { return ('0' <= c && c <= '9') || c == '-' || c == '+' || c == '.' || c == 'e'|| c == 'E'; }
bool startsWith(const std::string& prefix) const
{
return zen::startsWith(makeStringView(pos_, stream_.end()), prefix);
}
const std::string stream_;
std::string::const_iterator pos_;
};
class JsonParser
{
public:
JsonParser(const std::string& stream) :
scn_(stream),
tk_(scn_.getNextToken()) {} //throw JsonParsingError
JsonValue parse() //throw JsonParsingError
{
JsonValue jval = parseValue(); //throw JsonParsingError
expectToken(TokenType::eof); //
return jval;
}
private:
JsonParser (const JsonParser&) = delete;
JsonParser& operator=(const JsonParser&) = delete;
JsonValue parseValue() //throw JsonParsingError
{
if (token().type == TokenType::curlyOpen)
{
nextToken(); //throw JsonParsingError
JsonValue jval(JsonValue::Type::object);
if (token().type != TokenType::curlyClose)
for (;;)
{
expectToken(TokenType::string); //throw JsonParsingError
std::string name = token().primVal;
nextToken(); //throw JsonParsingError
consumeToken(TokenType::colon); //throw JsonParsingError
JsonValue value = parseValue(); //throw JsonParsingError
jval.objectVal.emplace(std::move(name), std::move(value));
if (token().type != TokenType::comma)
break;
nextToken(); //throw JsonParsingError
}
consumeToken(TokenType::curlyClose); //throw JsonParsingError
return jval;
}
else if (token().type == TokenType::squareOpen)
{
nextToken(); //throw JsonParsingError
JsonValue jval(JsonValue::Type::array);
if (token().type != TokenType::squareClose)
for (;;)
{
JsonValue value = parseValue(); //throw JsonParsingError
jval.arrayVal.emplace_back(std::move(value));
if (token().type != TokenType::comma)
break;
nextToken(); //throw JsonParsingError
}
consumeToken(TokenType::squareClose); //throw JsonParsingError
return jval;
}
else if (token().type == TokenType::string)
{
JsonValue jval(token().primVal);
nextToken(); //throw JsonParsingError
return jval;
}
else if (token().type == TokenType::number)
{
JsonValue jval(JsonValue::Type::number);
jval.primVal = token().primVal;
nextToken(); //throw JsonParsingError
return jval;
}
else if (token().type == TokenType::boolean)
{
JsonValue jval(JsonValue::Type::boolean);
jval.primVal = token().primVal;
nextToken(); //throw JsonParsingError
return jval;
}
else if (token().type == TokenType::null)
{
nextToken(); //throw JsonParsingError
return JsonValue();
}
else //unexpected token
throw JsonParsingError(scn_.posRow(), scn_.posCol());
}
const Token& token() const { return tk_; }
void nextToken() { tk_ = scn_.getNextToken(); } //throw JsonParsingError
void expectToken(TokenType t) //throw JsonParsingError
{
if (token().type != t)
throw JsonParsingError(scn_.posRow(), scn_.posCol());
}
void consumeToken(TokenType t) //throw JsonParsingError
{
expectToken(t); //throw JsonParsingError
nextToken(); //
}
Scanner scn_;
Token tk_;
};
}
inline
JsonValue parseJson(const std::string& stream) //throw JsonParsingError
{
return json_impl::JsonParser(stream).parse(); //throw JsonParsingError
}
}
#endif //JSON_H_0187348321748321758934215734
|