Open In App

How to Serialize JSON in JavaScript ?

JSON (JavaScript Object Notation) serialization is a fundamental concept in JavaScript, allowing the conversion of JavaScript objects into strings that can be easily transmitted over a network or stored in a file. We will explore how to serialize JSON in JavaScript using JSON.stringify().

Approach

In this approach, JSON.stringify() is used to serialize JavaScript objects into JSON strings. The first example demonstrates simple serialization of the person object without indentation. The second example shows serialization with indentation for better readability. It accepts three parameters: the object to serialize, a replacer function or array, and the spacing for indentation.

Example: The code below shows how to serialize JSON in JavaScript using Using JSON.stringify().

// Example 1: Simple object serialization
let person = { name: "John", age: 30, city: "New York" };
let jsonString = JSON.stringify(person);
console.log(jsonString);

// Example 2: Serialization with indentation
let jsonStringIndented = JSON.stringify(person, null, 2);
console.log(jsonStringIndented);

Output
{"name":"John","age":30,"city":"New York"}
{
  "name": "John",
  "age": 30,
  "city": "New York"
}
Article Tags :