custom parse function

by harsh dand

JavaScript

function parseJSON(jsonString) {
    // Check if input is a string
    if (typeof jsonString !== 'string') {
        throw new Error('Input must be a string');
    }

    // Remove whitespace from beginning and end of string
    jsonString = jsonString.trim();

    // Helper function to parse value
    function parseValue() {
        if (jsonString[0] === '{') {
            return parseObject();
        } else if (jsonString[0] === '[') {
            return parseArray();
        } else if (jsonString[0] === '"') {
            return parseString();
        } else if (jsonString[0] === 't' || jsonString[0] === 'f') {
            return parseBoolean();
        } else if (jsonString[0] === 'n') {
            return parseNull();
        } else {
            return parseNumber();
        }
    }

    // Helper function to parse object
    function parseObject() {
        let result = {};
        jsonString = jsonString.slice(1).trim(); // Remove '{'

        while (jsonString[0] !== '}') {
            let key = parseString();
            jsonString = jsonString.slice(1).trim(); // Remove ':'
            let value = parseValue();
            result[key] = value;

            if (jsonString[0] === ',') {
                jsonString = jsonString.slice(1).trim(); // Remove ','
            }
        }

        jsonString = jsonString.slice(1).trim(); // Remove '}'
        return result;
    }

    // Helper function to parse array
    function parseArray() {
        let result = [];
        jsonString = jsonString.slice(1).trim(); // Remove '['

        while (jsonString[0] !== ']') {
            let value = parseValue();
            result.push(value);

            if (jsonString[0] === ',') {
                jsonString = jsonString.slice(1).trim(); // Remove ','
            }
        }

        jsonString = jsonString.slice(1).trim(); // Remove ']'
        return result;
    }

    // Helper function to parse string
    function parseString() {
        let result = '';
   ...