JavaScript JSON.stringify: The Complete Guide

0
76
Javascript JSON.stringify() | How To Create JSON String

Number, Boolean, and String objects are converted to the corresponding primitive values during the stringification per traditional conversion semantics. Therefore, the undefined, Functions and Symbols are not valid JSON values.

If any such values are encountered during the conversion, they are either omitted(found in the object then omitted) or changed to null (if found in an array, then the value changes to null).

Javascript JSON.stringify

The JSON.stringify() is a built-in JavaScript function that allows us to take the Object or Array and create a JSON string.

JavaScript JSON.stringify() function converts the JavaScript object into a string, optionally replacing the values if the replacer function is specified or optionally including only the specified properties if the replacer array is specified. JSON.stringify() converts the value to JSON notation representing it.

JSON.stringify() converts the value to JSON notation representing it:

A value with the toJSON() method defines what data will be serialized.

JSON.stringify() can return the undefined when passing in “pure” values like JSON.stringify(function(){}) or JSON.stringify(undefined).

All Symbol-keyed properties will be ignored entirely, even when using a replacer function.

The instances of Date implement a toJSON() function by returning a string (the same as a date.toISOString()). Thus, they are treated as strings.

The numbers Infinity and NaN, and null, are all considered null.

All the other Object instances (including the Map, Set, WeakMap, and WeakSet) will have only their enumerable properties serialized.

Syntax

JSON.stringify(value, replacer, space)

Parameters

It accepts three parameters.

  1. value: It is the value to be converted into the JSON string.
  2. replacer: It is the optional parameter. This parameter value can be an altering function or the array used as a selected filter for the stringify. All object properties are included in the string if a value is empty or null.
  3. space: It is also an optional parameter. The space argument controls spacing in the final string generated using the JSON.stringify() function. It can be a number or string. If it is a number, then the specified number of spaces are indented to the final string, and if it is the string, that string is (up to 10 characters) used for indentation.

Example

Let’s convert an object to a string.

// app.js

let obj = { name: "Krunal", age: 27, city: "Rajkot" };
let jsonString = JSON.stringify(obj);
console.log(string);

See the output.

➜  es git:(master) ✗ node app
{"name":"Krunal","age":27,"city":"Rajkot"}
➜  es git:(master) ✗

The jsonString is now a string ready to be sent to a server.

How to Stringify JavaScript Array

To stringify an array in JavaScript, use the JSON.stringify() method.

// app.js

let arr = ['Millie Bobby Brown', 'Finn Wolfhard', 'Noah Schnapp'];
let jsonString = JSON.stringify(arr);
console.log(jsonString);

See the output.

➜  es git:(master) ✗ node app
["Millie Bobby Brown","Finn Wolfhard","Noah Schnapp"]
➜  es git:(master) ✗

Stringify JavaScript String

// app.js

let str = 'Eleven character in Stranger Things played by Millie';
let jsonString = JSON.stringify(str);
console.log(jsonString);

See the output.

➜  es git:(master) ✗ node app
"Eleven character in Stranger Things played by Millie"
➜  es git:(master) ✗

Stringify JavaScript Boolean, Integer

See the following code.

// app.js

let x = 11;
let y = true;

let jsonX = JSON.stringify(x);
let jsonY = JSON.stringify(y);

console.log(jsonX);
console.log(jsonY);

See the output.

➜  es git:(master) ✗ node app
11
true
➜  es git:(master) ✗

Stringify JavaScript Null, NaN, undefined

See the following code example.

// app.js

let x = null;
let y = undefined;
let z = NaN;
let jsonX = JSON.stringify(x);
let jsonY = JSON.stringify(y);
let jsonZ = JSON.stringify(z);
console.log(jsonX);
console.log(jsonY);
console.log(jsonZ);

See the output.

➜  es git:(master) ✗ node app
null
undefined
null
➜  es git:(master) ✗

JSON.stringify replacer parameter

The replacer parameter can be either the function or the array.

As a function, it takes two parameters: a key and a stringified value.

The object in which the key was found is provided as the replacer’s this parameter.

Initially, a replacer function is called with the empty string as the key representing an object being stringified.

It is then called for each property on the object or stringified array.

It should return a value that should be added to a JSON string, as follows:

  1. If you return the Number, the string corresponding to that number is used as a value for the property when added to a JSON string.
  2. If you return the String, that string is used as the property’s value when adding it to the JSON string.
  3. If you return the Boolean, “true” or “false” is used as a property’s value, as appropriate, when adding it to the JSON string.
  4. If you return the null value, null will be added to a JSON string.
  5. If you return any other object, an object is recursively stringified into the JSON string, calling the replacer function on each property unless the object is the function. In this case, nothing is added to the JSON string.
  6. If you return undefined, the property is not included (i.e., filtered out) in the output JSON string.

See the following code example.

// app.js

const replacer = (key, value) => {
  // Filtering out properties
  if (Number.isInteger(value)) {
    return undefined;
  }
  return value;
}

let shows = {
  hbo: 'Game of Thrones',
  netflix: 'Stranger Things',
  disneyplus: 'Mandalorian',
  appletvplus: 1
};
let res = JSON.stringify(shows, replacer);
console.log(res);

In the above function, if the value of the object property is Integer, then we filter it out, and the remaining data will be logged on the console.

➜  es git:(master) ✗ node app
{"hbo":"Game of Thrones","netflix":"Stranger Things","disneyplus":"Mandalorian"}
➜  es git:(master) ✗

JSON.stringify space parameter

The space argument may control the spacing in the final string.

  1. If it is a number, successive levels in the stringification will each be indented by the many space characters (up to 10).
  2. If it is the string, successive levels will be indented by this string (or the first ten characters of it).

See the following code example.

// app.js

const obj = {
  character: 'Eleven',
  actor: 'Millie'
}

console.log(JSON.stringify(obj, null, ' '));

See the output.

➜  es git:(master) ✗ node app
{
 "character": "Eleven",
 "actor": "Millie"
}
➜  es git:(master) ✗

How to find the length of JSON string

To find the length of the JSON String, use the length property.

// app.js

let jsonString = '{"name":"Millie Bobby Brown"}';
console.log("The string has " + jsonString.length + " characters");

See the output.

➜  es git:(master) ✗ node app
The string has 29 characters
➜  es git:(master) ✗

That’s it.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.