Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Convert Map to JSON in JavaScript ?
Next article icon

How to Convert JSON to string in JavaScript ?

Last Updated : 03 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Table of Content

  • Using JSON.stringify() Method
  • Using JSON.stringify() with Indentation
  • Using JSON.stringify() with Replacer Function
  • Using JSON.parse() followed by JSON.stringify() Method
  • Using a Custom Serializer Function
  • Using Template Literals

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"} 



Next Article
How to Convert Map to JSON in JavaScript ?

V

vishalkumar2204
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-string
  • JSON
  • JavaScript-Questions

Similar Reads

  • How to Convert String to JSON in JavaScript?
    In JavaScript, converting a string to JSON is important for handling data interchangeably between server and client, parsing external API responses, and storing structured data in applications. Below are the approaches to converting string to JSON in JavaScript: Table of Content Using JSON.parse()Us
    2 min read
  • How to Convert a Map to JSON String in JavaScript ?
    A Map is a collection of key-value pairs, where each key is unique. In this article, we will see how to convert a Map to a JSON (JavaScript Object Notation) string in JavaScript. However, JSON.stringify() does not directly support Map objects. Table of Content Using Object.fromEntries() MethodUsing
    2 min read
  • How To Convert Base64 to JSON String in JavaScript?
    There could be situations in web applications, where there is a need to decode the data from Base64 format back into its original JSON format. It generally happens when one has to transmit data over the network where Base64 encoding is well suited for encoding binary data. In this article, we will s
    2 min read
  • How to Convert Map to JSON in JavaScript ?
    In JavaScript, when working with data, you might encounter situations where you need to convert a Map object into a JSON format. This can be useful for sending data over the network, storing data in local storage, or interfacing with APIs that expect JSON data. Converting a Map to JSON means convert
    3 min read
  • 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 Conte
    2 min read
  • How to Convert XML to JSON in JavaScript?
    To convert XML to JSON in JavaScript, various methods and libraries and be used. Here, we use xml-js library that provides xml2json function to convert XML to JSON data. It takes XML data as input and gives the JSON objects as output. We can also use the DOMParser from the xmldom package to convert
    2 min read
  • How to Convert CSV to JSON in JavaScript ?
    In this article, we will explain different ways to change Comma-Separated Values (CSV) data into JavaScript Object Notation (JSON) format, step-by-step. We'll break down each method with clear explanations and examples. There are several approaches available in JavaScript to convert CSV to JSON in J
    3 min read
  • How to Convert String of Objects to Array in JavaScript ?
    This article will show you how to convert a string of objects to an array in JavaScript. You have a string representing objects, and you need to convert it into an actual array of objects for further processing. This is a common scenario when dealing with JSON data received from a server or stored i
    4 min read
  • How to Convert HTML to JSON in JavaScript ?
    Converting HTML to JSON is important for structured data extraction and integration with JavaScript applications. Here, we will learn different approaches to converting HTML to JSON in JavaScript. Below are the approaches to convert html to JSON in JavaScript: Table of Content Using html-to-json Lib
    2 min read
  • How to Convert JSON to Blob in JavaScript ?
    This article explores how to convert a JavaScript Object Notation (JSON) object into a Blob object in JavaScript. Blobs represent raw data, similar to files, and can be useful for various tasks like downloading or processing JSON data. What is JSON and Blob?JSON (JavaScript Object Notation): A light
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences