top of page

The Secrets of JSON.stringify()

Updated: Aug 1, 2023


JSON stringify

What is JSON.stringify()?

JSON.stringify() is a function commonly used to convert a JavaScript object or value to a JSON-formatted string. The JSON (JavaScript Object Notation) format is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate.


In JavaScript, the JSON.stringify() function is part of the built-in JSON object, and it serves the following purposes:

  1. Converting JavaScript Objects to JSON Strings: The function takes a JavaScript object or a value and converts it into a JSON-formatted string representation. This is useful when you want to serialize data (convert objects into a format that can be stored or transmitted) or send data in a format that can be easily understood by other systems or programming languages.

  2. Filtering and Formatting: The JSON.stringify() function also provides additional parameters to control the process of serialization. For example, you can use a "replacer" function to filter out specific properties or control the way values are stringified.

JSON.stringify Syntax:

JSON.stringify(value[, replacer[, space]])

Parameters:

  • value (required): The JavaScript object or value to be converted to a JSON string.

  • replacer (optional): A function or an array specifying which properties of the object should be included in the resulting JSON string. It can be used to filter or transform the values. If null or not provided, all properties are included.

  • space (optional): A string or number representing the number of spaces to use for pretty formatting the JSON string. If a number, the output will be formatted with that number of spaces; if a string, the string will be used as the indentation.


Return Value:

A JSON-formatted string representing the input JavaScript object or value.


Example:

const data = {
  name: 'Rahul',
  age: 36,
  city: 'INDIA'
};

const jsonString = JSON.stringify(data);
console.log(jsonString);
// Output: {"name":"Rahul","age":36,"city":"INDIA"}

Basic Usage:

When called with just one argument, JSON.stringify() transforms the JavaScript object into a JSON string. For example:

const obj = {
  name: "Rahul",
  age: 36,
};

const jsonString = JSON.stringify(obj);
console.log(jsonString);
/*
'{
"name":"Rahul",
"age":36
}'
*/

Dealing with Special Data Types:

However, there are certain data types that cannot be directly converted to JSON, such as Map, WeakMap, Set, WeakSet, and Error objects. When trying to stringify an object containing such types, they will be transformed into empty objects in the resulting JSON string. For example:

const snacksEatenToday = ['Cookie', 'Cookie', 'Chocolate bar', 'Cookie', 'Cookie'];

const obj = {
  name: "Rahul",
  uniqueSnacksEatenToday: new Set(snacksEatenToday),
};

const jsonString = JSON.stringify(obj);
/*
'{
"name":"Rahul",
"uniqueSnacksEatenToday":{}
}'
*/

Using the Second Argument - Replacer:

The second argument of JSON.stringify() is called the "replacer." It allows you to omit specific properties from the resulting JSON or transform their values. You can provide either an array or a function as the replacer.


Using an array as the replacer, you can include only the subset of properties you want to appear in the JSON output:

const obj = {
  name: "Peter",
  age: 36,
  password: "ILikeCookiesVeryMuch",
};

const jsonString = JSON.stringify(obj, ["name", "age"]);
/*
'{
"name":"Peter",
"age":36
}'
*/

Using a Function as the Replacer:

A function can be used as the replacer when you want more control over the transformation of object properties. The function takes two parameters, "key" and "value," and you can return the modified value for the property.

const snacksEatenToday = ['Cookie', 'Cookie', 'Chocolate bar', 'Cookie', 'Cookie'];

const obj = {
  name: "Rahul",
  age: 36,
  uniqueSnacksEatenToday: new Set(snacksEatenToday),
};

const transformer = (key, value) => {
  if (value instanceof Set) {
    return [...value.values()];
  }
  if (key === 'age') {
    if (value < 60) {
      return "Young";
    } else {
      return "Young, but life-experienced";
    }
  }
  return value;
};

const jsonString = JSON.stringify(obj, transformer);
/*
'{
"name":"Rahul",
"age":"Young",
"uniqueSnacksEatenToday":["Cookie","Chocolate bar"]
}'
*/

The Third Argument - Spacing:

The third argument of JSON.stringify() defines the spacing inside the resulting JSON string. It can be either a number or a string.


Using a number as the third argument adds that number of spaces for indentation:

const obj = {
  name: "Rahul",
  age: 63,
};
const jsonString = JSON.stringify(obj, null, 5);
/*
'{
     "name": "Rahul",
     "age": 36
}'
*/

Using a string as the third argument inserts the custom character(s) for indentation:

const obj = {
  name: "Rahul",
  age: 36,
};
const jsonString = JSON.stringify(obj, null, '💩💩💩');
/*
'{
💩💩💩"name": "Rahul",
💩💩💩"age": 36
}'
*/

Note: The maximum indentation level is 10, and any number above 10 will be cut down to 10. The third argument is not commonly used, but it may be helpful in certain situations for readability or as a way to add custom characters as spacing.


Conclusion

JSON.stringify is a powerful method in JavaScript that allows you to convert JavaScript objects or arrays into JSON strings. It serves as a fundamental tool for data serialization, enabling easy data exchange and storage. By understanding its syntax and capabilities, you can efficiently handle JSON data and integrate it into various applications.

bottom of page