Get AI Code Completions for Your IDE

Home   >   Tutorials   >   JavaScript   >   How to Use JSON.stringify in JavaScript

JavaScript - How to Use JSON.stringify in JavaScript

JavaScript Object Notation (JSON) is a lightweight data interchange format. It is commonly used to exchange data with a webserver.

When data is sent to a server it must be sent as a string.

JSON.stringify() method converts JavaScript data to a JSON-formatted string. It is usually applied to JS objects to produce a ready-made JSON string to be sent to the server.

Tip: You can use JSON.parse() to convert a JSON string back into a JavaScript object.

Basic example

Below is a basic example of how to use JSON.stringify() to convert a JavaScript object to a JSON string:

const user = {
  name: 'Danielle',
  age: 24,
  city: 'Seattle',
  admin: false
};
console.log(JSON.stringify(user));
// expected output: {"name":"Danielle","age":24,"city":"Seattle","admin":false}

In the above code, const user is a JavaScript object.

After stringifying, the object’s keys became strings. The values, however, are processed based on their type. For example, both age (type Number) and admin (type Boolean) were not converted to strings – they retained their original data type, and are not framed by double quotes in the final JSON string.

Note: functions on an object are not stringified, and will be removed from the object by the conversion process.

If you need to retain the functions in your JSON object, save them as strings using the toString() method or use the replacer parameter. More details are available below in the Syntax section.

Syntax

The syntax of JSON.stringify() is as follows:

JSON.stringify(value, replacer, space)

  • value: the item to convert to a JSON string.
  • replacer (optional): can be used to make changes to the item before stringifying.

replacer has two potential formats – it can be provided as a function or an Array. More details on this are presented below. If this parameter is empty or set to null, the stringifying process includes all of the object’s properties, but no functions.

  • space (optional): this is used for readability reasons only. JSON strings can sometimes be packed densely, making them difficult for developers to read. This parameter defines what type of whitespace or characters, if any, appears before each key in the JSON notation. More details on this are presented below.

replacer (optional parameter)

The replacer keyword, as stated above, can be used to make changes to the object before performing the stringify. The parameter can be a function or an Array – we cover both formats below.

replacer function

Use the following syntax to define a replacer parameter as a function:

Syntax

function replacer (key, value) {

conditional statement

return value

}

The parameters key and value represent the keys and values of the object being stringified. The object itself is set as the this pointer for the replacer.

The conditional statement is used to determine in which cases the replacer should take action.

Return value:

The return value of the replacer function determines what happens with the property being evaluated. When the return value is set to be a Number, String, Boolean, or null, the stringified version of the value will be set as the property’s value in the JSON output.

However, when the return value is set to Function, Symbol, or undefined, the property will not be included in the output. This happens because these values are not supported for stringifying.

When the return value is an object, the object return will be subject to the replacer’s condition and its specified outcome.

replacer function Example

Let us explore how to convert a function to a string in order to keep it in the stringified object:

const user = {
  name: 'Danielle',
  age: 24,
  city: 'Seattle',
  admin: false,
  greet: function greet() {
    return 'Hello World!'
  }
};
function replacer(key, value) {
  if (typeof value === 'function') {
    return value.toString()
  }
  return value
}
const userStringified = JSON.stringify(user, replacer, 3);
console.log(userStringified); 
  //expected output:
  // {
  //     "name": "Danielle",
  //     "age": 24,
  //     "city": "Seattle",
  //     "admin": false,
  //     "greet": "function greet() {\r\n        return 'Hello World!'\r\n    }"
  //  }

In the example above, greet was added as a key to the user object, and its value set to function greet().

The replacer function’s condition checks if the value is of type function. If so, it applies the toString() method to it and returns the value to the calling method. Otherwise, the replacer will not make any changes to the value, letting stringify() handle the data as it sees fit.

Since greet() is now a string, it can be stringified, thus it will be contained in the resulting JSON notation.

Note: The output’s display here is significantly different than the prior JSON example. This is due to the use of the space parameter. See the section on space below for more information.

Replacer array example

The following example shows how to use the replacer parameter with an array:

console.log(JSON.stringify(user, ['name', 'age']));
//expected output: {"name":"Danielle","age":24}

Note: The user object passed in here is the same object used in the previous example.

In this example, the replacer is an array of strings that refer to keys in the user object. This array is used to control which keys and values get stringified – fields will only be included in the output if they are present in the provided array.

space (optional parameter)

The space parameter controls the display of the JSON string. The parameter can be either a Number or a String.

When a Number is provided it represents the number of blank spaces between the start of a line in the JSON output to where the converted string begins. 10 is the maximum value allowed – any number greater than 10 is treated as 10. anything less than 1 is treated as a zero. See the example provided above for the behavior when a number is specified.

Alternatively it is possible to provide a String (up to 10 characters) which is then inserted at the start of each line. You can use blank spaces (e.g. ‘ ‘) or any other characters you desire. All strings are truncated to be no more than 10 characters. The example below demonstrates using a string value for the space parameter:

console.log(JSON.stringify(user, ['name', 'age'], '\t @>'));
//expected output: 
// {
//     @>"name": "Danielle",
//     @>"age": 24
// }

In the above example, \t is the control character for a tab space. The resulting JSON thus has a tab space before each key, which is then followed by @>.

The space parameter can be a significant help when working with large objects.

 

Related Articles:

JavaScript – Data types Explained

JavaScript – How to use the toString method

JavaScript – How to Change CSS

Get AI Code Completions for Your IDE