Skip to main content

JSON.stringify() (Live Playground)

In JavaScript, you might need to convert JavaScript objects to JSON strings when sending data to a server or saving it to a file. The JSON.stringify() method provides an easy way to achieve this. In this tutorial, we will explore how to stringify JavaScript objects and customize the process using replacer functions and space arguments.

Stringifying JavaScript Objects with JSON.stringify()

JSON.stringify() accepts a JavaScript object as its argument and returns a JSON string representation of the object.

Example:

const jsObject = {
firstName: 'John',
lastName: 'Doe',
age: 30,
};

const jsonString = JSON.stringify(jsObject);
console.log(jsonString); // Output: {"firstName":"John","lastName":"Doe","age":30}
Live Playground, Try it Yourself

Using Replacer Functions with JSON.stringify()

JSON.stringify() accepts an optional second argument, a replacer function, which allows you to control how the object is stringified. The replacer function is called for each key-value pair in the object, and you can use it to modify or filter the data.

Example:

const jsObject = {
firstName: 'John',
lastName: 'Doe',
age: 30,
};

const jsonString = JSON.stringify(jsObject, (key, value) => {
if (key === 'age') {
return value + 1;
}
return value;
});

console.log(jsonString); // Output: {"firstName":"John","lastName":"Doe","age":31}
Live Playground, Try it Yourself

Formatting JSON Strings with the Space Argument

JSON.stringify() also accepts an optional third argument, the space argument, which allows you to control the formatting of the JSON string. Providing a positive number or a string will indent the output with the specified number of spaces or the provided string.

Example:

const jsObject = {
firstName: 'John',
lastName: 'Doe',
age: 30,
};

const jsonString = JSON.stringify(jsObject, null, 2); // Indent with 2 spaces
console.log(jsonString);

// Output:
// {
// "firstName": "John",
// "lastName": "Doe",
// "age": 30
// }
Live Playground, Try it Yourself

Conclusion

JSON.stringify() is a powerful method for converting JavaScript objects to JSON strings. By understanding how to use replacer functions and the space argument, you can customize and format the JSON output for various use cases.