Open In App

How to Convert String to JSON in TypeScript ?

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Converting a string to JSON is essential for working with data received from APIs, storing complex data structures, and serializing objects for transmission.

Below are the approaches to converting string to JSON in TypeScript:

Convert String to JSON Using JSON.parse()

In this approach, we will make use of JSON.parse() function which parses a JSON string and converts it into a JavaScript object. It takes a single argument, which is a valid JSON-formatted string.

Syntax:

JSON.parse( string, function(optional) )

Example: The below code will explain the use of the JSON.parse() method to convert a string in JSON.

JavaScript
const jsonString: string =
    `{
        "name": "GeeksforGeeks", 
        "est": "2009", 
        "CEO": "Sandeep Jain"
    }`;

const jsonObject = 
    JSON.parse(jsonString);

console.log(jsonObject);
console.log(jsonObject.name);

Output:

{
name: "GeeksforGeeks",
est: "2009",
CEO: "Sandeep Jain"
}
name: "GeeksforGeeks"

Convert String to JSON Using eval()

In this approach, we will use eval() function which is a global function in JavaScript that evaluates a string of JavaScript code in the context from which it's called.

Syntax:

eval(codeString)

Example: The below code provides the implementation to convert string to JSON using eval().

JavaScript
const jsonString: string = `{
    "name": "GFG", 
    "est": 2009, 
    "type": "EdTech"
}`;
const jsonObject = 
    eval('(' + jsonString + ')');
console.log(jsonObject);

Output:

{
name: 'GFG',
est: 2009,
type: 'EdTech'
}

Convert String to JSON Using Function Constructor

In this approach, we will use Function() constructor which creates a function that returns a Javascript Object parsed to it.

Example: The below code example implements the Function() constructor which returns the Javascript Object.

JavaScript
const jsonString: string = `{
    "Platform": "GeeksforGeeks", 
    "type": "EdTech"
}`;
const jsonObject =
    new Function('return ' + jsonString)();

console.log(jsonObject);

Output:

{ 
Platform: 'GeeksforGeeks',
type: 'EdTech'
}

Using JSON.parse() with reviver function for date parsing

In this approach we are using JSON.parse() with a custom reviver function. The function examines each key-value pair during parsing, enabling specific transformations, such as converting date strings to Date objects, before returning the parsed JSON object.

Example: In this example we parses a JSON string, converting the "foundedDate" property to a Date object using a reviver function. It then logs the "name" property and checks if "foundedDate" is a Date.

JavaScript
const jsonStringWithDate: string = `{
    "name": "GeeksforGeeks",
    "foundedDate": "2009-01-01T00:00:00.000Z"
}`;

const jsonObjectWithDate = JSON.parse(jsonStringWithDate, (key, value) => {
    if (key === 'foundedDate') {
        return new Date(value);
    }
    return value;
});

console.log(jsonObjectWithDate.name);
console.log(jsonObjectWithDate.foundedDate instanceof Date); 

Output:

GeeksforGeeks
true

Using Regular Expressions to Convert String to JSON

This method involves writing a custom function that utilizes regular expressions to identify patterns and key-value pairs in the string, which can then be converted into an object structure. This approach should be used with caution and primarily in controlled environments, as it can be vulnerable to security issues similar to eval() if not properly managed.

Example Below is an example of how you might write a function to parse a simple formatted string into a JSON object using regular expressions

JavaScript
function convertStringToJson(str: string): any {
    const obj: any = {};
    const keyValuePairPattern = /(\w+)\s*:\s*(['"]?)(.*?)\2/g;
    let match: RegExpExecArray | null;

    while ((match = keyValuePairPattern.exec(str)) !== null) {
        const key = match[1];
        let value = match[3];
        // Try to parse numbers and booleans or keep as string
        if (!isNaN(Number(value))) {
            value = Number(value);
        } else if (value.toLowerCase() === "true" || value.toLowerCase() === "false") {
            value = value.toLowerCase() === "true";
        }
        obj[key] = value;
    }

    return obj;
}

// Example usage
const jsonString = "name: 'TechTalks', year: 2021, active: true";
const jsonObject = convertStringToJson(jsonString);
console.log(jsonObject);

Output:

{
"name": "TechTalks",
"year": 2021,
"active": true
}

Using a Custom Parser Function

This approach involves creating a custom parser function to manually parse a JSON-like string into an object. This method allows for more control over the parsing process and can be tailored to specific needs or formats.

Example:

JavaScript
function customJsonParser(str: string): any {
    let index = 0;

    function parseValue(): any {
        skipWhitespace();
        if (str[index] === '{') return parseObject();
        if (str[index] === '[') return parseArray();
        if (str[index] === '"') return parseString();
        return parseLiteral();
    }

    function parseObject(): any {
        const obj: any = {};
        match('{');
        while (str[index] !== '}') {
            skipWhitespace();
            const key = parseString();
            skipWhitespace();
            match(':');
            const value = parseValue();
            obj[key] = value;
            skipWhitespace();
            if (str[index] !== '}') match(',');
        }
        match('}');
        return obj;
    }

    function parseArray(): any {
        const arr: any[] = [];
        match('[');
        while (str[index] !== ']') {
            arr.push(parseValue());
            skipWhitespace();
            if (str[index] !== ']') match(',');
        }
        match(']');
        return arr;
    }

    function parseString(): string {
        match('"');
        let result = '';
        while (str[index] !== '"') {
            result += str[index++];
        }
        match('"');
        return result;
    }

    function parseLiteral(): any {
        const start = index;
        while (index < str.length && !/[,\]}]/.test(str[index])) {
            index++;
        }
        const literal = str.slice(start, index).trim();
        if (literal === 'null') return null;
        if (literal === 'true') return true;
        if (literal === 'false') return false;
        if (!isNaN(Number(literal))) return Number(literal);
        throw new SyntaxError('Unexpected token');
    }

    function match(char: string): void {
        if (str[index] === char) {
            index++;
        } else {
            throw new SyntaxError(`Expected '${char}' at position ${index}`);
        }
    }

    function skipWhitespace(): void {
        while (/\s/.test(str[index])) {
            index++;
        }
    }

    return parseValue();
}

// Example usage
const jsonString = '{"name": "TechTalks", "year": 2021, "active": true, "features": ["workshops", "webinars"]}';
const jsonObject = customJsonParser(jsonString);
console.log(jsonObject);

Output:

{
"name": "TechTalks",
"year": 2021,
"active": true,
"features": ["workshops", "webinars"]
}

Converting String to JSON Using a Third-Party Library

In this approach, we will use the json5 library, which allows for a more flexible JSON syntax. JSON5 is an extension of JSON that aims to make JSON easier to write and maintain. It allows for comments, trailing commas, single-quoted strings, and more. This can be particularly useful when dealing with JSON data that is hand-written or needs to support a more human-readable format.

Example: The below code demonstrates the use of the json5 library to convert a string to JSON.

JavaScript
const JSON5 = require('json5');

const jsonString = `
{
    name: 'TechTalks',
    year: 2021,
    active: true,
    features: ['workshops', 'webinars']
}
`;

const jsonObject = JSON5.parse(jsonString);
console.log(jsonObject);

Output:

{
"name": "TechTalks",
"year": 2021,
"active": true,
"features": ["workshops", "webinars"]
}

Next Article

Similar Reads