Knowing a proper methodology is necessary for any aspiring developer when working with JSON files. The same applies to learning how to convert JavaScript objects or values into JSON strings. That’s when the JSON.stringify()
method will be handy for coping with such coding challenges.
Basics of JSON.stringify()
For the most part, the JSON.stringify()
method converts a particular value or object to a JSON string. Optionally, this method can replace values if a replacer function is specified beforehand. See this method syntax to understand what parameters it works with:
JSON.stringify(value, replacer, space)
As seen, this method can include up to three parameters:
value
refers to a value, which has to be converted to a JSON string.
replacer
is an optional parameter that alters the behavior of the command by naming the values that should not be included in the final output. In other words, if you omit the replacer, all object properties will be included in the JSON string.
space
is another optional parameter used to insert a space to a String
or Number
object. Omitting this parameter will result in the output having no white spaces.
Once we know what parameters form the JSON.stringify()
method, let’s review the basic use case:
const user = {
name: 'Robert',
age: 24,
city: 'Barcelona',
admin: true
};
console.log(JSON.stringify(user)); // Expected output: {"name":"Robert","age":24,"city":"Barcelona","admin":true}
We’ve provided a user, also specifying other related properties, such as name, age, city, and admin. Once we log the JSON.stringify() method through a console, we get the key-value pairs; all depicted as strings. Now, let’s review how optional parameters work.
Using a replacer parameter
Replacer parameter is optional, but its application allows smart output filtering using the JSON.stringify()
method. See the example how the replacer parameter can be used to filter out the properties, removing string results from the output:
function replacer(key, value) {
if (typeof value === 'string') {
return undefined;
}
return value;
}
const example1 = {company: 'Microsoft', software: 'Windows', version: 11};
console.log(JSON.stringify(example1, replacer, )); // Expected output: {"version":11}
In this case, we’ve included the example1 array, which consists of the company name, software it develops, and its current version. Pay attention that we include the if loop to specify that it returns undefined if the value equals string. That’s why the expected output of the provided example will only include the value, which has no string inside of it, which is {“version”: 11}
.
Experimenting with a space parameter
Even though the space parameter is also optional, getting some hands-on experience with it won’t hurt:
console.log(JSON.stringify({ example: 7 }, null, 'wow'));
// Expected output: {
// wow"example": 7
// }
In this case, we log the JSON.stringifty()
method to a console, with a key-value of an object, a null parameter, and a string. The output you get shows how the space parameter separates data values and presents them differently.
Since we’ve indicated that ‘wow’ is a space, it impacts the final output modified with this string. Take a look at how you can use the space parameter using a tab character and see how it modifies the output:
console.log(JSON.stringify({ example: 7 }, null, '\t'));
// Expected output: {
// wow"example": 7
// }
In this case, when you use the tab character, the output you get reflects how the space operator works. Feel free to test it with any value you like and see how the expected output changes depending on your input.
Note: when specifying a custom space and use non-whitespace values, in most cases the JSON becomes invalid, which means that the call of JSON.parse() will return an error:
“Uncaught SyntaxError: Unexpected string”
Custom toJSON use
We’ve previously mentioned that you can use the toJSON()
method for a proper to-JSON conversion. In this instance, the JSON.stringify()
method is automatically called to work with the data you input properly.
However, this approach changes the usual code behavior. Instead of a particular object being serialized, the value returned to the toJSON()
will be serialized. To omit any misunderstanding with serialization, kindly review the following example:
const obj = {
dog: 'dog',
toJSON (key) {
if (key)
return Now, I am the dog nested under key' ${key}';
else
return this;
}
};
console.log(JSON.stringify(obj));
// Expected output: {"dog":"dog"}
console.log(JSON.stringify({ obj }));
// Expected output: {"obj":"Now, I am the dog nested under key' obj'"}
console.log(JSON.stringify([ obj ]));
// Expected output: ["Now, I am the dog nested under key' 0'"]
What we have here might look confusing, but it all becomes more apparent when you debunk the code snippet step-by-step:
We call the toJSON()
if the object is a property value and the property name, returning {“dog”: “dog”}
.
When it is located in an array, we get the index in the array as a string.
Finally, we use the JSON.stringifty()
method with an empty string to directly call it on the object.
Test yourself
Task 1. Use the
JSON.stringify()
method for the following value pairs related to a user:name: ‘Bob,’ age: ‘28,’ city: ‘Rome,’ admin: false
.
Solution:
const user = {
name: 'Bob',
age: 28,
city: 'Rome',
admin: false
};
console.log(JSON.stringify(user)); // Expected output: {"name":"Bob","age":28,"city":"Rome","admin":false}
Task 2. Use the
JSON.stringify()
method for the following values and log them through a console: NaN, null, Infinity.
Solution:
console.log(JSON.stringify([NaN, null, Infinity])); // Expected output: [null,null,null]
Task 3. Try using the
JSON.stringify()
method with the same input as in Task 1, only this time use a replacer ‘string,’ and a tab character:
function replacer(key, value) {
if (typeof value === 'string') {
return undefined;
}
return value;
}
const user = {
name: 'Bob',
age: 28,
city: 'Rome',
admin: false
};
console.log(JSON.stringify(user, replacer, '\t'));
// Expected output: {
// "age": 28,
// "admin": false
//}
Conlusion
As you can see through dozens of examples, the JSON.stringify()
method has a flexible range of applications for JavaScript developers. While its primary function is to convert an object or the value into the JSON string, you can experiment with the optional replacer and space parameters.