How to Create JSON String in JavaScript?
JSON strings are widely used for data interchange between a server and a client, or between different parts of a software system. So converting objects to JSON strings is very important for good client-server communication.
Below are the following approaches to creating a JSON string:
Table of Content
Using JSON.stringify( ) method
We can directly convert a Javascript object to a JSON string using the JSON.stringify( ) method where we pass the object as an argument. The output will be a string following the JSON notation.
Example: In this example, we will create a Javascript object and convert it into a JSON string.
// Creating a JavaScript object
let obj = new Object();
obj.name = 'Mohit';
obj.department = 'CSE(Data Science)';
obj.age = 20;
// Converting JS object to JSON string
let json_string = JSON.stringify(obj);
console.log(json_string);
Output
{"name":"Mohit","department":"CSE(Data Science)","age":20}
Using Template literals
Template literals provide a more readable and dynamic way to construct JSON strings compared to traditional string concatenation.The template literal syntax, enclosed by backticks (`), allows for multiline strings and interpolation of variables using ${}.
Example: This example shows the use of the above-explained approach.
let name = "Mohit";
let department = "CSD";
let age = 20;
let JSON_string = `{
"name": "${name}",
"department": "${department}",
"age": "${age}"
}`;
console.log(JSON_string);
Output
{ "name": "Mohit", "department": "CSD", "age": "20" }