#2759
Hard JavaScript Convert json string to object
61.3% acceptance
Mar 31, 2026
17
3
Given a string str, return parsed JSON parsedStr. You may assume the str is a valid JSON string hence it only includes strings, numbers, arrays, objects, booleans, and null. str will not include invisible characters and escape characters.
Please solve it without using the built-in JSON.parse method.
Solution
TypeScript
Time O(n³)
Space O(1)
type JSONValue =
| null
| boolean
| number
| string
| JSONValue[]
| { [key: string]: JSONValue };
function jsonParse(str: string): JSONValue {
let i = 0;
function parseValue(): JSONValue {
if (str[i] === '"') return parseString();
if (str[i] === "{") return parseObject();
if (str[i] === "[") return parseArray();
if (str[i] === "t") {
i += 4;
return true;
}
if (str[i] === "f") {
i += 5;
return false;
}
if (str[i] === "n") {
i += 4;
return null;
}
return parseNumber();
}
function parseString(): string {
i++; // skip opening quote
let result = "";
while (str[i] !== '"') {
result += str[i++];
}
i++; // skip closing quote
return result;
}
function parseNumber(): number {
let start = i;
if (str[i] === "-") i++;
while (i < str.length && str[i] >= "0" && str[i] <= "9") i++;
if (str[i] === ".") {
i++;
while (i < str.length && str[i] >= "0" && str[i] <= "9") i++;
}
if (str[i] === "e" || str[i] === "E") {
i++;
if (str[i] === "+" || str[i] === "-") i++;
while (i < str.length && str[i] >= "0" && str[i] <= "9") i++;
}
return Number(str.slice(start, i));
}
function parseArray(): JSONValue[] {
i++; // skip [
const arr: JSONValue[] = [];
if (str[i] === "]") {
i++;
return arr;
}
arr.push(parseValue());
while (str[i] === ",") {
i++;
arr.push(parseValue());
}
i++; // skip ]
return arr;
}
function parseObject(): { [key: string]: JSONValue } {
i++; // skip {
const obj: { [key: string]: JSONValue } = {};
if (str[i] === "}") {
i++;
return obj;
}
let key = parseString();
i++; // skip :
obj[key] = parseValue();
while (str[i] === ",") {
i++;
key = parseString();
i++; // skip :
obj[key] = parseValue();
}
i++; // skip }
return obj;
}
return parseValue();
}