Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
JSON Syntax
3.
JSON.stringify()
3.1.
Syntax
3.2.
Parameter
3.3.
Return Value
4.
Using JSON.stringify()
4.1.
The Replacer Parameter
4.1.1.
As a function
4.1.2.
As an array
4.2.
The Space Parameter
5.
Frequently Asked Questions
6.
Key Takeaways
Last Updated: Mar 27, 2024

JSON.stringify()

Author Gunjeev Singh
1 upvote

Introduction

Javascript Object Notation is a standardized file format used for data interchange between services, programs, and users. The JSON object in Javascript contains methods for resolving JSON and converting values to JSON formats. JSON is a light and efficient way of transferring and storing data. It is the most used format in web services and server-client interactions.

To simplify the concept of JSON, it is merely a syntax for serializing objects, arrays, numbers, strings, booleans, and NULL. In this blog, we will look into the first of the two methods in the JSON object of the Javascript Engine. 

You can head to this guided path prepared specially for Javascript beginners to learn more about Javascript.

JSON Syntax

Before we start learning about the JSON.parse() method, let us understand the basic syntax of the JSON. There are a few rules of the JSON method which can be summed up like:

  • The data is always kept in name and value pairs
  • Commas must separate all data
  • Objects are held by curly braces, while square brackets have arrays.

A sample JSON object could be:

{
"students":[
{"firstName":"John", "lastName":"Appleseed"},
{"firstName":"Anna", "lastName":"Jones"},
{"firstName":"Pete", "lastName":"Smith"}
]
}

In the above example, “students” is an array of three objects. Shown above is the basic JSON syntax. JSON syntax becomes vital to learn since JSON is the preferred way of transferring data between web applications and servers. 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

JSON.stringify()

There are two methods in the JSON. The first method is used for Parsing data, while the second method converts data into a string. Perhaps the most common use of JSON is transferring data between servers on the web. While sending data to a web server, the data must be a string. This is where the JSON.stringify() method comes into play.

Syntax

We can use the JSON.stringify() method in three different ways. Let us now look at all of them.

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

These three variations differ from each other in the parameters that they accept.

Parameter

Parameter

Description

Value This is what the actual Javascript object is. We need to convert this value to a string using the JSON.stringify() method.
Replacer This is an optional parameter. This is usually a function or an array that allows us to filter the parts of the Javascript Object that will be stringified. If this parameter is not provided, the entire Javascript object is converted to a JSON string. 
Space The space parameter is usually a string or a number. It is used to add whitespaces in the resultant string for better readability. If the space parameter is a number, it denotes the number of whitespaces to add. If it is a string, the string is used as whitespace. 

 

Return Value

Since the JSON.stringify() converts Javascript objects into JSON string, the return value is JSON string. At certain instances of errors, like the input not being valid or conversion not being possible, the return value can also be undefined.

Using JSON.stringify()

The expected behavior of the JSON.stringify() in possible permutations of inputs can be seen below using the following examples:

JSON.stringify({});                                  // The return value would be - '{}'
JSON.stringify(true);                             // The return value would be -  'true'
JSON.stringify('helloworld');                 // The return value would be - ‘"helloworld"'
JSON.stringify([1, 'false', false]);         // The return value would be -  '[1,"false",false]'
JSON.stringify([NaN, null, Infinity]);   // The return value would be -  '[null,null,null]'
JSON.stringify({ y: 0 });                     // The return value would be -  '{"y":0}'

The Replacer Parameter

As discussed above, the replacer parameter is either a function or an array.

As a function

It takes two parameters - a key and a value being stringified as a function. Initially, the replacer function runs with an empty string and the key denoting the Javascript object. Then, it is called for each property of the object being stringified.

It then returns the value which is added to the JSON string under the following conditions:

  1. If a String, Boolean, Number, or NULL is returned, the stringified version of that value is used. 
  2. If a Function, Symbol, or Undefined is returned, the property is not included in the string.
  3. If an object is returned, the replacer function is called recursively on each property. 

Example:

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

 
var sample = {company: 'CN', vertical: 'blogs', week: 4, month: 12};
console.log(JSON.stringify(sample, replacer));

Output:

{"week":4,"month":12}

 

As an array

If the replacer argument is an array, the array’s values denote the names of the properties that the method should include in the stringification process.

Example:

var sample = {company: 'CN', vertical: 'blogs', week: 4, month: 12};
console.log(JSON.stringify(sample, ['week', 'month']));

Output:

{"week":4,"month":12}

The Space Parameter

As discussed above, the space parameter controls the whitespaces in the resultant final string. It can either be a number or a string. Many spaces will succeed at each level in the stringification process if it is a number. If it is a string, successive levels will be indented by this string.

Try and compile by yourself with the help of online javascript compiler for better understanding.

Frequently Asked Questions

1. What is the role of the toJSON property name?
Ans.If the given object has a property named toJSON, whose value is a function, then the toJSON() method modifies the stringification process. Instead of the value being a serialized value, the returning value from the toJSON method will be serialized.

 

2. What are the exceptions to the JSON.stringify() function?
Ans.We cannot give circular references to the JSON.stringify() method. The function throws a TypeError when a BigInt value is being converted.

Key Takeaways

This blog explained the JSON.stringify method. We first looked at the basic JSON syntax. Then we looked at the variations of JSON.stringify before going into greater detail about every parameter of the method. We have now covered both the methods for JSON - parse and stringify. 

Recommended problems -

Head over to our web development blogs to continue your learning journey!

Previous article
XML
Next article
AJAX introduction
Live masterclass