DEV Community

Cover image for Everything about JSON Stringify Method - JavaScript
Jitendra
Jitendra

Posted on • Edited on

Everything about JSON Stringify Method - JavaScript

Overview

JavaScript provides a static method JSON.stringify(). Which is useful to convert valid JavaScript object to JSON string.

Apart from it this method comes with lot of flexibility to create JSON string using using its replacer and space arguments.

In this article, we will explore how use to them.

To stringify JSON data online you can use a popular online tool JSON to String.

Syntax

JSON.stringify(value, replacer, space)
Enter fullscreen mode Exit fullscreen mode

Parameters of JSON.stringify

  1. Value (mandatory)
  2. Replacer (optional)
  3. Space (optional)

1. Value Parameter

Value is required to be passed as a parameter when calling the function.

const user = {
  "name": "Jimmy",
  "age": 67,
  "city": "New York"
};

const user_string = JSON.stringify(user);
Enter fullscreen mode Exit fullscreen mode

Output

`{"name":"Jimmy","age":67,"city":"New York"}`
Enter fullscreen mode Exit fullscreen mode

2. Replacer Parameter

Replacer is a optional parameter. It can be either an array or a function to alter the JavaScript object before converting it JSON string.

Assume you have your personal information in the form of a JavaScript object and now you want to convert it to JSON string. The issue is that you don't want to include all of the keys in the JSON string. Here replacer parameter comes into picture to apply that filter.

As an array, It will contain a list of allowed keys which you want to include in the result of JSON stringify.

const user = {
    "username": "johndoe",
    "firstName": "John",
    "lastName": "Doe",
    "email": "johndoe@dev.to",
    "age": 30,
    "registrationDate": "2023-09-12T12:00:00Z"
}

const replacer = ['username', 'firstName', 'lastName'];

const userData_string = JSON.stringify(user, replacer);

console.log(userData_string); 

Enter fullscreen mode Exit fullscreen mode

Output

`{"username":"johndoe","firstName":"John","lastName":"Doe"}`
Enter fullscreen mode Exit fullscreen mode

As a function, It takes two parameters (Key, Value).

function replacer_function (key, value) {    
    // code
}
Enter fullscreen mode Exit fullscreen mode

Consider a case where you want to add some logic to altering JSON data (Ex - You want to stringify an object's keys that does not contain string values).

const user = {
  "name": "John Doe",
  "age": 30,
  "email": "johndoe@example.com",
  "isSubscribed": true
}

function replacer(key, value){
    if(typeof value === 'string'){
        return undefined;
    }
    return value;
}

const user_string = JSON.stringify(user, replacer);


Enter fullscreen mode Exit fullscreen mode

Output

`{"age":30,"isSubscribed":true}`
Enter fullscreen mode Exit fullscreen mode
  • When replacer returns a object, string, number, boolean, or null, That returned value is treated as the value of the property, and the method converts it to a JSON string.

  • When it returns function, undefined or symbol, method will skip that key and will not include in output.

3. Space Parameter

We can use space parameter to control spacing in final result.
When we do not use last parameter, By default stringify method returns very crowded and dense output.

Space as a Number

When we use space as a number, the output's key-value pairs are separated by the specified number of spaces.

If we discuss the Space Parameter restriction. Only 0 to 10 spacing is allowed.

const colors = {
    primary: ['red','blue','green'],
    secondary: ['cyan', 'magenta', 'yellow'],
    tertiary: ['yellow-orange', 'red-orange', 'red-purple']
}

const colors_string = JSON.stringify(colors, null, 3);
console.log(colors_string);
Enter fullscreen mode Exit fullscreen mode

Output

`{
   "primary": [
      "red",
      "blue",
      "green"
   ],
   "secondary": [
      "cyan",
      "magenta",
      "yellow"
   ],
   "tertiary": [
      "yellow-orange",
      "red-orange",
      "red-purple"
   ]
}`
Enter fullscreen mode Exit fullscreen mode

Space as a String

If string is used as a space parameter. JSON stringify method will indent the result by the provided string.

const data = {
  name: "Central Park",
  city: "New York",
  country: "United States",
  amenities: ["Playgrounds", "Walking Trails", "Pond"],
};
const data_string = JSON.stringify(data, null, "fire");
console.log(data_string)
Enter fullscreen mode Exit fullscreen mode

Output

`{
fire"name": "Central Park",
fire"city": "New York",
fire"country": "United States",
fire"amenities": [
firefire"Playgrounds",
firefire"Walking Trails",
firefire"Pond"
fire]
}`
Enter fullscreen mode Exit fullscreen mode

I hope this was helpful to understand how JSON stringify works in JavaScript.

Top comments (0)