How to create JSON String in Javascript

 How to create JSON String in Javascript

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.

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);

See the output.

➜  es git:(master) ✗ node app
➜  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);

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);

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);


See the output.

➜  es git:(master) ✗ node app
➜  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);

See the output.

➜  es git:(master) ✗ node app
➜  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);

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.

JSON Tutorial For Beginners | What is JSON | Learning JSON with JavaScript

JSON Tutorial For Beginners | What is JSON | Learning JSON with JavaScript

JSON Tutorial For Beginners | What is JSON | Learning JSON with JavaScript

Explore JSON and how JavaScript Objects can be used to access data within JSON data format and output to your web page

Guide to learning how to use JavaScript Objects and JSON data. JSON is the most popular format for data exchange between applications. If you are interested in connected to a web API chances are its JSON formatted. Learn to use AJAX to connect and bring JSON data into your JavaScript!

This course shows you how to work with JSON formatted data, output content, loop JSON data, Parse JSON and a whole lot more.

JSON (JavaScript Object Notation) is a syntax for data. JSON is easier to use than XML and human readable. Most modern web APIs output data in JSON formats. It's a lightweight data interchange format that is quickly becoming the default format for data exchange on internet today! JSON is lightweight, language independent and easy to read and write. JSON is better than XML and more popular!

Within the lessons of this course we will explore

  • JavaScript data types used to hold variables and how they work
  • JSON and how to write JSON data
  • How to add values into a JSON object
  • Accessing JSON data and bringing it into JavaScript
  • JavaScript JSON parse and stringify methods
  • Adding JSON to local storage
  • Retrieving back data within JSON formats, updating and working with JSON
  • Connecting to a web API using fetch
  • Retrieving JSON data from a web API and outputting the results into your web page
  • Iterating threw multiple results from an API
  • Google Spreadsheet data as JSON and how to practice retrieving data
  • All of the source code and resources are in included
  • Explore different methods of working with the JSON data stringify and parsing
  • How JavaScript objects can use Arrays to hold multiple items
  • How JavaScript arrays work and store data

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about JavaScript and JSON

The Complete JavaScript Course 2019: Build Real Projects!

JavaScript Programming Tutorial | Full JavaScript Course for Beginners 2019

The complete beginner’s guide to JSON

The Complete Guide to JSON Web Tokens

JWT Fundamentals for Beginners

Best JavaScript Frameworks, Libraries and Tools to Use in 2019

New ES2019 Features Every JavaScript Developer Should Know

How to use JSON.stringify() and JSON.parse() in JavaScript

How to use JSON.stringify() and JSON.parse() in JavaScript

JSON.stringify() and JSON.parse() are useful tools for handling JSON-formatted content

There are two useful methods to deal with JSON-formatted content: JSON.stringify() & JSON.parse(), which are useful to learn as a pair.

JSON.parse() takes a JSON string and then transforms it into a JavaScript object.

const myObject = {
  dog: "🐕",
  cat: "🐈",
  koala: "🐨",
  count: 3

// result: {"dog":"🐕","cat":"🐈","koala":"🐨","count":3}

// result: Object {dog: "🐕", cat: "🐈", koala: "🐨", count: 3}

JSON.stringify() can take arguments, a replacer function and a string or number to use as a “space” in the returned string.

That means the replacer argument can be used to filter out values if you return undefined, as shown in the following example:

const user = {
  id: 101010,
  name: "Derek",
  email: "[email protected]"

function replacer(key, value) {
  if (typeof value === "number") {
    return undefined;
  if (key === "email") {
    return "Removed for privacy";
  return value;

// result: {"id":101010,"name":"Derek","email":"[email protected]"}

console.log(JSON.stringify(user, replacer));
// {"name":"Derek","email":"Removed for privacy"}

console.log(JSON.stringify(user, null, "^_^ "));
// result: {
// ^_^ "id": 101010,
// ^_^ "name": "Derek",
// ^_^ "email": "[email protected]"
// }

// result: Object {id: 101010, name: "Derek", email: "[email protected]"}

How do you spell stringify backwards? JSON.parse() (Photo by clement fusil on Unsplash)