How to Convert JSON to string in JavaScript ?
Last Updated :
03 Jul, 2024
In this article, we are going to learn the conversion of JSON to string in JavaScript. Converting JSON to a string in JavaScript means serializing a JavaScript object or data structure represented in JSON format into a textual JSON string for data storage or transmission.
Several methods can be used to Convert JSON to string in JavaScript, which are listed below:
We will explore all the above methods along with their basic implementation with the help of examples.
Approach 1: Using JSON.stringify() Method
In this approach, JSON.stringify() in JavaScript converts JSON data into a formatted string representation.
Syntax:
JSON.stringify(value, replacer, space);
Example: In this example, we are using the above-explained method.
JavaScript
const data = { name: "Nikita", age: 21, city: "Noida" };
const result = JSON.stringify(data);
console.log(result);
Output{"name":"Nikita","age":21,"city":"Noida"}
Approach 2: Using JSON.stringify() with Indentation
In this approach, using JSON.stringify() in JavaScript, specifying optional parameters for indentation to format JSON data into a more readable and structured string representation for debugging or visualization.
Syntax:
const result = JSON.stringify(data, null, 2);
Example: In this example we are using the above-explained approach.
JavaScript
const data = { name: "Aman", age: 21, city: "Noida" };
const result = JSON.stringify(data, null, 2);
console.log(result);
Output{
"name": "Aman",
"age": 21,
"city": "Noida"
}
Approach 3: Using JSON.stringify() with Replacer Function
In this approach, we use JSON.stringify() with a custom replacer function in JavaScript to transform or omit specific values while converting JSON data to a string representation.
Syntax:
const result = JSON.stringify(data, (key, value) => {
if (typeof value === "number") {
// Modify number values
return value * 2;
}
return value;
});
Example: In this example we are using the above-explained approach.
JavaScript
const data = { name: "Rahul", age: 30, city: "Delhi" };
const result = JSON.stringify(data, (key, value) => {
if (typeof value === "number") {
// Modify number values
return value * 2;
}
return value;
});
console.log(result);
Output{"name":"Rahul","age":60,"city":"Delhi"}
Approach 4: Using JSON.parse() followed by JSON.stringify() Method
In this approach, we convert JSON string to a JavaScript object using JSON.parse(), then convert the object back to a JSON string using JSON.stringify()
Syntax:
const jsonObject = JSON.parse(str1);
const result = JSON.stringify(jsonObject);
Example: In this example, we Parse str1 into a JavaScript object, store as jsonObject, then convert back to JSON string using JSON.stringify(jsonObject).
JavaScript
const str1 = '{"key1":"value1","key2":"value2"}';
const jsonObject = JSON.parse(str1);
const result = JSON.stringify(jsonObject);
console.log(result);
Output{"key1":"value1","key2":"value2"}
Approach 5: Using a Custom Serializer Function
In this approach, we create a custom serializer function that allows more control over how the JSON data is converted to a string. This can include additional custom processing, such as handling special data types or applying specific transformations to the data.
Example: In this example, we create a custom function that converts Date objects to ISO strings and omits the 'password' property.
JavaScript
const data = {
name: "John",
age: 35,
city: "New York",
birthdate: new Date("1989-06-15"),
password: "secret123"
};
function customStringify(obj) {
return JSON.stringify(obj, (key, value) => {
if (value instanceof Date) {
return value.toISOString();
}
if (key === 'password') {
return undefined;
}
return value;
});
}
const result = customStringify(data);
console.log(result);
Output{"name":"John","age":35,"city":"New York","birthdate":"1989-06-15T00:00:00.000Z"}
Approach 6: Using Template Literals
Using template literals to convert a JSON object to a string involves mapping over the object's entries and formatting each key-value pair as a string. This approach leverages JavaScript's Object.entries method and template literals for concise and readable code.
Example:
JavaScript
const jsonObj = { name: "John", age: 30 };
const jsonString = `{${Object.entries(jsonObj).map(([key, value]) =>
`"${key}":"${value}"`).join(',')}}`;
console.log(jsonString); // '{"name":"John","age":30}'
Output{"name":"John","age":"30"}
Similar Reads
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial
React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
HTML Interview Questions and Answers
HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
NodeJS Interview Questions and Answers
NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
What is an API (Application Programming Interface)
In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Introduction of Firewall in Computer Network
A firewall is a network security device either hardware or software-based which monitors all incoming and outgoing traffic and based on a defined set of security rules it accepts, rejects, or drops that specific traffic. It acts like a security guard that helps keep your digital world safe from unwa
10 min read
Web Development Technologies
Web development refers to building, creating, and maintaining websites. It includes aspects such as web design, web publishing, web programming, and database management. It is the creation of an application that works over the internet, i.e., websites.Core Concepts of Web Development TechnologiesWeb
8 min read