How to Convert String to JSON in TypeScript ?
Last Updated :
01 Aug, 2024
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"]
}
Similar Reads
How to Convert String to Number in TypeScript?
In TypeScript, converting a string to a number is a common operation that can be accomplished using several different methods. Each method offers unique advantages and can be chosen based on the specific requirements of your application. Below are the approaches to convert string to number in TypeSc
4 min read
How to Convert Map to JSON in TypeScript ?
In TypeScript, we can convert the Map to JSON by manipulating the key-value pairs of the Map into JSON-formatted string. We can use various approaches like JSON.stringify, fast-json-stringify, and json-stringify-safe Libraries for the conversion. Table of Content Using JSON.stringifyUsing fast-json-
5 min read
How to Convert an Object to a JSON String in Typescript ?
In TypeScript, an object is a collection of related data and functionality. Objects are made up of properties and methods. Properties describe the object, methods describe what it can do. Table of Content Using JSON.stringify()Using json-stringify-safe libraryUsing a Custom Serialization FunctionUsi
5 min read
How to Convert String to Date in TypeScript ?
In TypeScript, conversion from string to date can be done using the Date object and its method. We can use various inbuilt methods of Date object like new Date() constructor, Date.parse(), and Date.UTC. Table of Content Using new Date()Using Date.parse() Using Date.UTC()Using new Date()In this appro
2 min read
How to Convert a String to enum in TypeScript?
In TypeScript, an enum is a type of class that is mainly used to store the constant variables with numerical and string-type values. In this article, we will learn, how we can convert a string into an enum using TypeScript. These are the two approaches that can be used to solve it: Table of Content
5 min read
How to Convert String to Boolean in TypeScript ?
In Typescript, sometimes you receive the data as strings but need to work with boolean values or identify the boolean equivalent of it. There are several approaches to convert string to boolean in TypeScript which are as follows: Table of Content Using Conditional StatementUsing JSON.parse() MethodU
4 min read
How to Convert Typescript Dictionary to String ?
In TypeScript, dictionaries are often represented as the objects where keys are associated with the specific values. Converting a TypeScript dictionary to a string is an important task when doing API calls where we cast the JSON response from the API to a string. Below are the ways to convert a Type
5 min read
How to Convert a Bool to String Value in TypeScript ?
When we talk about converting a boolean to a string value in TypeScript, we mean changing the data type of a variable from a boolean (true or false) to a string (a sequence of characters). We have multiple approaches to convert a bool to a string value in TypeScript. Example: let's say you have a va
4 min read
How to parse JSON string in Typescript?
In this tutorial, we will learn how we can parse a JSON string in TypeScript. The main reason for learning about it is to learn how we can explicitly type the resulting string to a matching type. The JSON.parse() method will be used to parse the JSON string by passing the parsing string as a paramet
4 min read
How to Format Strings in TypeScript ?
Formatting strings in TypeScript involves combining and structuring text to produce clear and readable output. This practice is essential for creating dynamic and user-friendly applications, as it allows developers to seamlessly integrate variables and expressions into strings, enhancing the overall
3 min read