How to useJSON.parse() followed by JSON.stringify() Method in Javascript
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).
const str1 = '{"key1":"value1","key2":"value2"}';
const jsonObject = JSON.parse(str1);
const result = JSON.stringify(jsonObject);
console.log(result);
Output
{"key1":"value1","key2":"value2"}
How to Convert JSON to string in JavaScript ?
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.
There are several methods that can be used to Convert JSON to string in JavaScript, which are listed below:
- Using JSON.stringify() Method
- Using JSON.stringify() with Indentation
- Using JSON.stringify() with Replacer Function
- Using JSON.parse() followed by JSON.stringify() Method
We will explore all the above methods along with their basic implementation with the help of examples.