-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSON.parse.js
More file actions
99 lines (78 loc) · 2.24 KB
/
JSON.parse.js
File metadata and controls
99 lines (78 loc) · 2.24 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
// https://bigfrontend.dev/problem/implement-JSON-parse
function parse(jsonString) {
let index = 0;
function parseValue() {
const currentChar = jsonString[index];
if (currentChar === '{') {
return parseObject();
} else if (currentChar === '[') {
return parseArray();
} else if (currentChar === '"') {
return parseString();
} else if (currentChar === 't' || currentChar === 'f') {
return parseBoolean();
} else if (currentChar === 'n') {
return parseNull();
} else {
return parseNumber();
}
}
function parseObject() {
let obj = {};
index++; // skip '{'
while (jsonString[index] !== '}') {
const key = parseString();
index++; // skip ':'
const value = parseValue();
obj[key] = value;
if (jsonString[index] === ',') {
index++; // skip ','
}
}
index++; // skip '}'
return obj;
}
function parseArray() {
let arr = [];
index++; // skip '['
while (jsonString[index] !== ']') {
const value = parseValue();
arr.push(value);
if (jsonString[index] === ',') {
index++; // skip ','
}
}
index++; // skip ']'
return arr;
}
function parseString() {
let str = '';
index++; // skip '"'
while (jsonString[index] !== '"') {
str += jsonString[index];
index++;
}
index++; // skip '"'
return str;
}
function parseBoolean() {
const boolStr = jsonString.slice(index, index + 4);
index += 4; // skip 'true' or 'false'
return boolStr === 'true';
}
function parseNull() {
index += 4; // skip 'null'
return null;
}
function parseNumber() {
let numStr = '';
while (/[\d.+\-eE]/.test(jsonString[index])) {
numStr += jsonString[index];
index++;
}
return parseFloat(numStr);
}
return parseValue();
}
const jsonStr = '{"yo":"biro","a":{"b":{"c":[1],"nyc":"pik"}}}';
console.log(parse(jsonStr))