Skip to content

Commit aa56159

Browse files
authored
Create convert-json-string-to-object.ts
1 parent ff705a9 commit aa56159

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// Time: O(n)
2+
// Space: O(h)
3+
4+
// stack
5+
function jsonParse(str: string): any {
6+
let stk = [];
7+
let result = null;
8+
let k = null;
9+
for (let i = 0; i < str.length; i++) {
10+
if (str[i] === "," || str[i] === ":") {
11+
continue;
12+
}
13+
if (str[i] === '{' || str[i] === '[') {
14+
let v = str[i] === '{' ? {} : [];
15+
if (result !== null) {
16+
if (k !== null) {
17+
result[k] = v;
18+
k = null;
19+
} else {
20+
result.push(v);
21+
}
22+
stk.push(result);
23+
}
24+
result = v;
25+
} else if (str[i] === '}' || str[i] === ']') {
26+
if (stk.length !== 0) {
27+
result = stk.pop();
28+
}
29+
} else {
30+
let v;
31+
if (str[i] === '-' || ('0' <= str[i] && str[i] <= '9')) {
32+
let j = i;
33+
while (i + 1 < str.length &&
34+
(str[i + 1] === '-' || ('0' <= str[i + 1] && str[i + 1] <= '9') || str[i + 1] === '.')) {
35+
i++;
36+
}
37+
v = Number(str.substring(j, i + 1));
38+
} else if (str[i] === '"') {
39+
let j = i + 1;
40+
while (i + 1 < str.length && str[i + 1] !== '"') {
41+
i++;
42+
}
43+
v = str.substring(j, i + 1);
44+
i++;
45+
} else {
46+
if (i + 3 < str.length && str.substring(i, i + 4) === "true") {
47+
v = true;
48+
i += 3;
49+
} else if (i + 4 < str.length && str.substring(i, i + 5) === "false") {
50+
v = false;
51+
i += 4;
52+
} else {
53+
v = null;
54+
i += 3;
55+
}
56+
}
57+
if (result === null) {
58+
result = v;
59+
} else if (str[i + 1] === ":") {
60+
k = v;
61+
} else if (k !== null) {
62+
result[k] = v;
63+
k = null;
64+
} else {
65+
result.push(v);
66+
}
67+
}
68+
}
69+
return result;
70+
};

0 commit comments

Comments
 (0)