How To Convert an Object to a JSON in Typescript

While programming, we often want to convert an Object to a JSON to be able to interact with the API. We will use a built-in method that is JSON.stringify(). Let’s find out together.

Convert an object to JSON in TypeScript

Use JSON.stringify()

In TypeScript, we’ll use the JSON.stringify() method to convert the object to a JSON string. The TypeScript JSON.stringify() method is used to generate a JSON string from it. As we continuously develop applications using TypeScript, it is necessary to serialize data into an array for storing data in a database or sending data to an API or web server. Data must be in string format. Converting an object to a string is easily done using the JSON.stringify() method.

The Syntax of JSON.stringify()

JSON.stringify(object, replacer, space)

Parameters:

object: is the object to be converted to a JSON string.
replacer: is a function that changes the behavior of the chain or a set of strings and numbers that specify the value properties to be added to the result. If the modifier is not a function or a string (for example, null or not specified), then all properties in the string’s key object are included in the resulting JSON string.
space: is used to add spaces (including indentation, line breaks, etc.) to the output JSON string for readability.
If it is a number, it specifies the number of spaces used as indentation, compressed to 10 (i.e., any number greater than 10 is considered 10). Values less than 1 indicate that spaces should not be used.

Return Value:

Returns a json string of the input object

Example:

let student = {
	name: "Mary",
	age: 20,
	gender: "Female",
	address: "New York City, New York",
};

// Using JSON.stringify() method to convert an Object to a JSON
let jsonData = JSON.stringify(student);
console.log(jsonData);

Output:

{"name":"Mary", "age":20, "gender":"Female", "address":"New York City, New York"}

Use JSON.stringify() and JSON.parse()

Let’s say we want to parse it back to the previous object. We use the JSON.parse() method to parse a JSON string to create a TypeScript object defined by that string.

Example:

let student = {
	name: "Mary",
	age: 20,
	gender: "Female",
	address: "New York City, New York",
};

// Using JSON.stringify() method to convert an Object to a JSON
let jsonData = JSON.stringify(student);

//Using JSON.parse() to parse it back to the previous object
let studentObject = JSON.parse(jsonData);
console.log(studentObject);

Output:

{
  "name": "Mary",
  "age": 20,
  "gender": "Female",
  "address": "New York City, New York"
}

Summary

This article taught us how to convert an Object to a JSON in Typescript using JSON.stringify(). This is a convenient and widely used method. Hope the article is useful to you, good luck.

Leave a Reply

Your email address will not be published. Required fields are marked *