文章目錄
  1. 1. JSON 和Context-free Grammar的關係
  2. 2. Sample Code

JSON 和Context-free Grammar的關係

Copy from JSON.org

object
  {}
  { members }
members
  pair
  pair , members
pair
  string : value
array
  []
  [ elements ]
elements
  value 
  value , elements
value
  string
  number
  object
  array
  true
  false
  null

JSON 可以由Context-free Grammar 所做成。當中的rule都是non-ambiguous,內裡的leftmost derivation, 都是deterministic (只有一個方法)。而且可以先做rule1 再做rule2。因此他是LL(1) parser, 可以用predictive parsing,用recursive decent method.

每次先看看一個character 然後決定走那條rule
下面是sample code,當中的members和elements 不用recursion那麼深… 可以用while 取代, syntax error detection 的做法參加了原作者, 一檢測到就throw exception

Sample Code

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
public class JSONValidator {
private String jsonString;
private int idx = -1; // next scan character index

public JSONValidator(String jsonString) {
this.jsonString = jsonString;
this.idx = 0;
}

public char peek() {
return jsonString.charAt(idx);
}


public void next(char expectedChar) {
if (peek() != expectedChar) {
// run time exceptions
throw new JSONParseException("Expected " + expectedChar + " at " + idx + " but " + peek() + " is found");
}

idx++;
}


public void next() {
idx++;
}

public void parse() {
object();
}

public void object() {
ws();
next('{');
ws();
if (peek() == '}') {
// System.out.println("Empty JSON Object");
next('}');
} else {
members();
ws();
next('}');
}
}

public void members() {
ws();
pair();
ws();


if (isEnd()){
throw new JSONParseException("Unexpected ending of JSON Object, may be missing } ");
}

if (peek() == ',') {
next(',');
members();
}
}

public void pair() {
ws();
String key = string();
System.out.println("Key in json object: " + key);
ws();
next(':');
ws();
String value = value();
System.out.println("Value in json object: " + value);
}

public String value() {
ws();

if (isEnd()){
throw new JSONParseException("Expected a JSON value at " + idx);
}

char ch = peek();
String returnStr = "";

switch (ch){
case '{' :
object();
break;
case '[' :
array();
break;
case '"' :
return string();
case '-':
return number();
default:
returnStr = (Character.isDigit(ch)) ? number() : word() + "";
}

return returnStr;
}

public String word() {
char ch = peek();
switch (ch) {
case 't':
next('t');
next('r');
next('u');
next('e');
return "true";
case 'f':
next('f');
next('a');
next('l');
next('s');
next('e');
return "false";
case 'n':
next('n');
next('u');
next('l');
next('l');
return "null";
default:
throw new JSONParseException("Unknowned token " + ch + " at " + idx);
}

}

public void array() {
ws();
next('[');
ws();

if (peek() == ']'){
next(']'); // empty array;
} else {
elements();
ws();
next(']');
}
}

public void elements() {
ws();
String value = value();
System.out.println("value of array elements: " + value);
ws();
if (peek() == ','){
next(',');
elements();
}
}

public boolean isEnd() {
return idx >= jsonString.length();
}

/** skip white Space */
public void ws() {
while (!isEnd()) {
if (Character.isWhitespace(peek())) {
idx++;
} else {
break;
}
}
}

public String number() {
ws();
int initIdx = idx;

String numberString = "";
if (peek() == '-'){
next('-');
numberString += '-';
}

// digit before .
while (!isEnd()) {
char c = peek();
if (Character.isDigit(c)) {
numberString += c;
idx++;
} else {
break;
}
}

if (isEnd()){
throw new JSONParseException("Unexpected number at the end");
}

// digit after .
if (peek() == '.'){
next('.');
numberString += '.';

while (!isEnd()) {
char c = peek();
if (Character.isDigit(c)) {
numberString += c;
idx++;
} else {
break;
}
}
}

// integer or double
try {
System.out.println("Parse as Int for " + numberString);
return Integer.parseInt(numberString) + "";
} catch (NumberFormatException ex){
try {
System.out.println("Parse as double for " + numberString);
return Double.parseDouble(numberString) + "";
} catch (NumberFormatException ex2){
throw new JSONParseException("Expected number at " + initIdx + " but it is not found");
}
}

}

public int nextInt() {
ws();

String intStr = "";
while (!isEnd()) {
char c = peek();
if (Character.isDigit(c)) {
intStr += c;
idx++;
} else {
break;
}
}

return Integer.parseInt(intStr);
}

/* next string without "" */
public String string() {
ws();

String str = null;
boolean scanning = false;

char c = peek();
if (c == '"') {
scanning = true;
str = "";
next();
}

while (!isEnd() && scanning) {
c = peek();

if (c == '"') {
scanning = false;
next();
} else {
str += c;
next();
}
}

return str;
}


}

文章評論

文章目錄
  1. 1. JSON 和Context-free Grammar的關係
  2. 2. Sample Code