AppDividend
Latest Code Tutorials

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

0

Javascript JSON.stringify() 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.

Javascript JSON.stringify()

The JSON.stringify() is the inbuilt function in which it allows us to take the JavaScript Object or Array and create a JSON string out of it.

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

If a value has the toJSON() method, it’s responsible for defining what data will be serialized.

Number, Boolean, and String objects are converted to the corresponding primitive values during the stringification, in accord with a traditional conversion semantics.

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 object then omitted) or changed to null (if found in an array then value changes to null).

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 date.toISOString()). Thus, they are treated as the 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)

It accepts three parameters.

  1. value: It is the value that is 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. If a value is empty or null, then all properties of the object included in the string.
  3. space: It is also an optional parameter. The space argument is used to control spacing in the final string generated using the JSON.stringify() function. It can be number or string if it is a number than the specified number of spaces indented to the final string, and if it is the string, then that string is (up to 10 characters) used for indentation.

#JSON.stringify Example

Let’s convert Javascript object to 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, and ready to be sent to a server.

#Stringify JavaScript Array

In the above example, we have stringify the Javascript Object.

Let’s stringify the Javascript Array.

// 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

Let’s pass the string and see the output.

// 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 value that being stringified.

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 an array that being stringified.

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 which 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 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 be used to 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 length of JSON string

Let’s find a length of JSON string.

// 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) ✗

Finally, Javascript JSON.stringify() | How To Create JSON String Example is over.

Recommended Posts

Javascript JSON.parse()

PHP json_encode()

How To Convert Python Dictionary To JSON

PHP json_decode Example

How To Parse JSON in Python

Leave A Reply

Your email address will not be published.

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