-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathjson_parser.cpp
140 lines (121 loc) · 3.74 KB
/
json_parser.cpp
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
/**
* This example demonstrate how we can use peg_parser::parser parse standard
* JSON. https://en.wikipedia.org/wiki/JSON#Data_types_and_syntax
*/
#include <peg_parser/generator.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <variant>
#include <vector>
/** Class to store JSON objects */
struct JSON {
enum Type { NUMBER, STRING, BOOLEAN, ARRAY, OBJECT, EMPTY } type;
std::variant<double, std::string, bool, std::vector<JSON>, std::map<std::string, JSON>> data;
explicit JSON(double v) : type(NUMBER), data(v) {}
explicit JSON(std::string &&v) : type(STRING), data(v) {}
explicit JSON(bool v) : type(BOOLEAN), data(v) {}
explicit JSON(std::vector<JSON> &&v) : type(ARRAY), data(v) {}
explicit JSON(std::map<std::string, JSON> &&v) : type(OBJECT), data(v) {}
explicit JSON() : type(EMPTY) {}
};
/** Print JSON */
std::ostream &operator<<(std::ostream &stream, const JSON &json) {
switch (json.type) {
case JSON::NUMBER: {
stream << std::get<double>(json.data);
break;
}
case JSON::STRING: {
stream << '"' << std::get<std::string>(json.data) << '"';
break;
}
case JSON::BOOLEAN: {
stream << (std::get<bool>(json.data) ? "true" : "false");
break;
}
case JSON::ARRAY: {
stream << '[';
for (auto v : std::get<std::vector<JSON>>(json.data)) stream << v << ',';
stream << ']';
break;
}
case JSON::OBJECT: {
stream << '{';
for (auto v : std::get<std::map<std::string, JSON>>(json.data)) {
stream << '"' << v.first << '"' << ':' << v.second << ',';
}
stream << '}';
break;
}
case JSON::EMPTY: {
stream << "null";
break;
}
}
return stream;
}
/** Define the grammar */
peg_parser::ParserGenerator<JSON> createJSONProgram() {
peg_parser::ParserGenerator<JSON> g;
g.setSeparator(g["Separators"] << "[\t \n]");
g["JSON"] << "Number | String | Boolean | Array | Object | Empty";
// Number
g.setProgramRule("Number", peg_parser::presets::createDoubleProgram(),
[](auto e) { return JSON(e.evaluate()); });
// String
g.setProgramRule("String", peg_parser::presets::createStringProgram("\"", "\""),
[](auto e) { return JSON(e.evaluate()); });
// Boolean
g["Boolean"] << "True | False";
g["True"] << "'true'" >> [](auto) { return JSON(true); };
g["False"] << "'false'" >> [](auto) { return JSON(false); };
// Array
g["Array"] << "'[' (JSON (',' JSON)*)? ']'" >> [](auto e) {
std::vector<JSON> data(e.size());
std::transform(e.begin(), e.end(), data.begin(), [](auto v) { return v.evaluate(); });
return JSON(std::move(data));
};
// Object
g["Object"] << "'{' (Pair (',' Pair)*)? '}'" >> [](auto e) {
std::map<std::string, JSON> data;
for (auto p : e) {
data[std::get<std::string>(p[0].evaluate().data)] = p[1].evaluate();
}
return JSON(std::move(data));
};
g["Pair"] << "String ':' JSON";
// Empty
g["Empty"] << "'null'" >> [](auto) { return JSON(); };
g.setStart(g["JSON"]);
return g;
}
/** Input */
int main() {
using namespace std;
auto json = createJSONProgram();
cout << "Enter a valid JSON expression.\n";
while (true) {
string str;
cout << "> ";
getline(cin, str);
if (str == "q" || str == "quit") {
break;
}
try {
auto result = json.run(str);
cout << "Parsed JSON: " << result << endl;
} catch (peg_parser::SyntaxError &error) {
auto syntax = error.syntax;
cout << " ";
cout << string(syntax->begin, ' ');
cout << string(syntax->length(), '~');
cout << "^\n";
cout << " "
<< "Syntax error while parsing " << syntax->rule->name << endl;
}
}
return 0;
}