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 | type JSONValue =
| null
| boolean
| number
| string
| JSONValue[]
| { [key: string]: JSONValue };
class JSONParser {
private str: string;
private i: number;
constructor(str: string) {
this.str = str;
this.i = 0;
}
public parse(): JSONValue {
return this.parseValue();
}
private parseValue(): JSONValue {
switch (this.str[this.i]) {
case '{':
return this.parseObject();
case '[':
return this.parseArray();
case 't': // true
case 'f': // false
case 'n': // null
return this.parseLiteral();
case '"':
return this.parseString();
default:
return this.parseNumber();
}
}
private parseObject(): JSONValue {
++this.i;
const ans: JSONValue = {};
while (this.i < this.str.length && this.str[this.i] !== '}') {
const key = this.parseString();
this.expectChar(':');
const value = this.parseValue();
ans[key] = value;
if (this.str[this.i] === ',') {
++this.i;
}
}
++this.i;
return ans;
}
private parseArray(): JSONValue[] {
++this.i;
const ans: JSONValue[] = [];
while (this.i < this.str.length && this.str[this.i] !== ']') {
const value = this.parseValue();
ans.push(value);
if (this.str[this.i] === ',') {
++this.i;
}
}
++this.i;
return ans;
}
private parseLiteral(): boolean | null {
if (this.str.startsWith('true', this.i)) {
this.i += 4;
return true;
}
if (this.str.startsWith('false', this.i)) {
this.i += 5;
return false;
}
if (this.str.startsWith('null', this.i)) {
this.i += 4;
return null;
}
throw new Error(`Unexpected token at position ${this.i}`);
}
private parseString(): string {
let ans = '';
++this.i;
while (this.i < this.str.length && this.str[this.i] !== '"') {
ans += this.str[this.i];
++this.i;
}
++this.i;
return ans;
}
private parseNumber(): number {
let start = this.i;
if (this.str[this.i] === '-') {
++this.i;
}
while (this.i < this.str.length && this.isDigit(this.str[this.i])) {
++this.i;
}
if (this.str[this.i] === '.') {
++this.i;
while (this.i < this.str.length && this.isDigit(this.str[this.i])) {
++this.i;
}
}
return Number(this.str.slice(start, this.i));
}
private isDigit(n: string): boolean {
return n >= '0' && n <= '9';
}
private expectChar(char: string): void {
if (this.str[this.i] !== char) {
throw new Error(`Expected '${char}' at position ${this.i}`);
}
++this.i;
}
}
function jsonParse(str: string): JSONValue {
const parser = new JSONParser(str);
return parser.parse();
}
|