Use JSON.stringify() and JSON.parse() in JavaScript

Last Updated on by in JavaScript

JavaScript JSON.Stringify() Method

JSON.Stringify() will be uncovered in this article. Common JSON operations in JavaScript.We are going to start with the full form of JSON – JavaScript Object Notation. JSON is a readable, minified format for data structuring.

We use it as a replacement for XML. The most basic purpose of JSON is to transmit data between a web application and a server.

Keys and Values

When it comes to JSON, keys and values are the most critical aspects. It primarily functions with a key/value pair.

Type Info
Key A string you find inside a quotation mark is what is regarded as a key.
Value: As for a value, it can be an object, array, Boolean expression, number or string.

Key/Value pair:

It has a specific syntax. It is represented like this -> Key: value. You will be using commas to separate key/value pairs.

The most important thing about JSON is that all modern browsers support it. To deal with the JSON-formatted content, it makes use of stringify and parse.

Let’s Understand JSON.stringify()

To begin with, JSON.Stringify() is a function which is inbuilt in JSON. With the help of it, you can create a JSON string from a JavaScript Array or Object. When you develop an application using JavaScript, you may have noticed that you need to come up with data in the serialized format in strings so that it can be saved to the database or can be sent to a web browser or API.

Having the data in the string form is crucial. So this conversion of Arrays or Objects into a string is carried out efficiently by JSON.stringify() function.

Understand JSON.stringify() Syntax

JSON.stringify(value, replacer, space)

Let’s take a look at the 3 parameters accepted by JSON.stringify().

Value: We are referring to the value which is going to be converted into a JSON string here.

Replacer: Well, replacer is an optional parameter. As for the value of this parameter, it can be an array or altering function used as a selected filter for the JSON.stringify. In case the value is null or empty, then all properties of an object will be appended to the string.

Space: Again, it is an optional parameter for JSON.stringify JavaScript function. To control the spacing in the string generated eventually, you will be using this parameter. As for the value, you can either pass a string or number.

If you pass a number, then the specified number of spaces will be indented to the string. In case if you pass a string, this particular string will be used for indentation in the generated string.

Return Value: Yes, JSON.stringify() returns a string.

Examples of JSON.stringify() in JavaScript

JavaScript code to demonstrate the functioning of JSON.stringify() function:

// JSON.stringify Example
var myObject = { 
  name: "James", 
  age: 25, 
  location: "California"
};

var result = JSON.stringify(myObject);

// Output: {"name":"James","age":25,"location":"California"}

Converting an Object into a string using JSON.stringify() JavaScript Method

Let’s take a look at the code given below. We are passing a JavaScript object as a value to convert it into a string.

// JSON.stringify Example
var myObject = {
  name: "Cardi B",
  age: 23,
  location: "Michigan"
};

var result = JSON.stringify(myObject);

console.log("Output of result = " + result + "<br>");
// Output of result = {"name":"Cardi B","age":23,"location":"Michigan"}<br>

console.log("type of result = " + typeof result);
// type of result = string

Converting Array into String using JSON.stringify Method in JavaScript

We are going to examine another example. Here we have passed a JSON.stringify array as a value in order to convert it into a string.

// JSON.stringify Example
var myArray = ["Cardi B", "23", "Michigan"];

var result = JSON.stringify(myArray);

console.log("Output of result = " + result);
// Output of result = ["Cardi B","23","Michigan"]

console.log("type of result = " + typeof result);
// Output: type of result = string

Browser Support for JSON.stringify()

The JSON.stringify() function is supported by all the major browsers as well as the latest ECMAScript (JavaScript).

Chrome IE Firefox Safari Opera
Yes 8.0 3.5 4.0+ 10.0+

To know more detailed info on JSON.stringify() visit MDN Docs.

Getting Started with JSON.parse() JavaScript Method

JSON is used to exchange data from a web server. Data is always received in a string form from a web server. JSON.parse(), method helps to convert string data form into a JavaScript object.

You need to keep in mind that JSON doesn’t support trailing commas. So you should not strings with trailing commas to the JSON.parse() function. In case you did, the function will throw a syntax error.

// JSON.parse() Example
var myObj = '{ "name": "Black Widow", "age": 32, "city": "New York" }';

var result = JSON.parse(myObj);
// Output: { name: "Black Widow", age: 32, city: "New York"}

How to Get JSON From the Web Server?

Getting JSON data from the web server is very easy, you have to make the AJAX request. If the data is received in JSON format, then you can easily parse the string into a JS object.

Use XMLHttpRequest to fetch the data from remote server.

// Fetching JSON Data from Remote Server
var http = new XMLHttpRequest();

http.onreadystatechange = function() {
  if (this.status == 200 && this.readyState == 4) {
    var result = JSON.parse(this.responseText);
      result.forEach(function(element) {
        console.log(element.name);
      })
  }
};

http.open("GET", "https://jsonplaceholder.typicode.com/users", true);
http.send();
// Result will be 

# Leanne Graham
# Ervin Howell
# Clementine Bauch
# Patricia Lebsack
# Chelsey Dietrich
# Mrs. Dennis Schulist
# Kurtis Weissnat
# Nicholas Runolfsdottir V
# Glenna Reichert
# Clementina DuBuque

Using the Reviver parameter with JSON.parse()

JSON.parse() can accept a 2nd argument for a reviver function. And it has the ability to transform the object values before the function returns them. In the following example, we have uppercased the object’s values using this method.

// Example JSON.parse()
const hero = {
  name: 'Captain America',
  email: 'captainamerica@mcu.com',
  designation: 'Super Hero'
};

const heroStr = JSON.stringify(hero);

JSON.parse(heroStr, (key, value) => {
  if (typeof value === 'string') {
    return value.toLowerCase();
  }
  return value;
});


/* 
Output will be:
captain america
captainamerica@mcu.com
super hero
*/

Browser Support for JSON.parse()

The JSON.parse() function works in almost all the major browsers as well as the latest ECMAScript (JavaScript).

Chrome IE Firefox Safari Opera
Yes 8.0 3.5 4.0+ 10.0+