This solution is generated by ChatGPT, correctness is not guaranteed.
AI solution for JavaScript Coding Question on BFE.dev
22. implement JSON.parse()
function parseJSON(jsonString) {
const index = { value: 0 };
function parseValue() {
const start = index.value;
let result;
switch (jsonString[start]) {
case '{':
result = parseObject();
break;
case '[':
result = parseArray();
break;
case '\"':
result = parseString();
break;
case 't':
result = parseTrue();
break;
case 'f':
result = parseFalse();
break;
case 'n':
result = parseNull();
break;
default:
result = parseNumber();
break;
}
return result;
}
function parseObject() {
index.value++;
const obj = {};
while (jsonString[index.value] !== '}') {
const key = parseString();
index.value++;
const value = parseValue();
obj[key] = value;
if (jsonString[index.value] === ',') {
index.value++;
}
}
index.value++;
return obj;
}
function parseArray() {
index.value++;
const arr = [];
while (jsonString[index.value] !== ']') {
const value = parseValue();
arr.push(value);
if (jsonString[index.value] === ',') {
index.value++;
}
}
index.value++;
return arr;
}
function parseString() {
const start = index.value + 1;
let end = start;
while (jsonString[end] !== '\"') {
if (jsonString[end] === '\\') {
end++;
}
end++;
}
const str = jsonString.slice(start, end);
index.value += str.length + 1;
return str;
}
function parseTrue() {
index.value += 4;
return true;
}
function parseFalse() {
index.value += 5;
return false;
}
function parseNull() {
index.value += 4;
return null;
}
function parseNumber() {
const start = index.value;
let end = start;
while ('0123456789-+eE.'.includes(jsonString[end])) {
end++;
}
const numStr = jsonString.slice(start, end);
const num = +numStr;
index.value += numStr.length;
return num;
}
return parseValue();
}