Skip to main content

Command Palette

Search for a command to run...

JavaScript JSON and toJSON Methods

Updated
•4 min read•View as Markdown
JavaScript JSON and toJSON Methods
B

Web technology related ➡️ blogger || video creator || author || online instructor || YouTuber || web developer || freelancer

The JSON.stringify syntax used so far is:

JSON.stringify(value)

The general syntax actually is:

JSON.stringify(value[, replacer, space])
  • replacer and space are optional.

replacer

The replacer is an array of properties to encode or a mapping function.

JSON.stringify(value, replacer)

The second argument, replacer filters out the circular references of an object.

replacer as an array

The replacer can be used as an array.

Syntax:

JSON.stringify(value, [ ... ])

See the example below:

const skill = {
  lang: 'JavaScript'
};

const occupation = {
  title: 'Junior software engineer',
  employees: [ {name: "Bob"}, {name: "James"} ],
  habbit: skill // occupation references skill
};

skill.work = occupation; // skill references occupation

console.log( JSON.stringify(occupation, ['title', 'employees']) );
// {"title":"Junior software engineer","employees":[{},{}]}

In the example above, the objects in employee are empty because the name is not in the list.

Let's include the name in the employee object (and key properties lang and habbit) below:

const skill = {
  lang: 'JavaScript'
};

const occupation = {
  title: 'Junior software engineer',
  employees: [ {name: "Bob"}, {name: "James"} ],
  habbit: skill // occupation references skill
};

skill.work = occupation; // skill references occupation

console.log( JSON.stringify(occupation, ['title', 'employees', 'name', 'lang', 'habbit']) );
// {"title":"Junior software engineer","habbit":{"lang":"JavaScript"}}

replacer as an function

The replacer can be used as a function.

Syntax:

JSON.stringify(value, function(key, value))

See the example below:

const skill = {
  lang: 'JavaScript'
};

const occupation = {
  title: 'Junior software engineer',
  employees: [ {name: "Bob"}, {name: "James"} ],
  habbit: skill // occupation references skill
};

skill.work = occupation; // skill references occupation

const replacer = (key, value) => {
  console.log(`${key}: ${value}`);
  return (key == 'work') ? undefined : value;
}

console.log( JSON.stringify(occupation, replacer) );

/*
: [object Object]
title: "Junior software engineer"
employees: [object Object],[object Object]
0: [object Object]
name: Bob
1: [object Object]
name: James
habbit: [object Object]
lang: JavaScript
work: [object Object]
{"title":"Junior software engineer","employees":[{"name":"Bob"},{"name":"James"}],"habbit":{"lang":"JavaScript"}}
*/

In the example above, the function will be called for every (key, value) pair.

For example

...
employees: [object Object],[object Object]
...

The first call : [object Object] has its key empty and the value, the target object as a whole.

The replacer analyzes or skips certain objects, or if possible the whole object.

space

space specifies the number of spaces to use for pretty formatting.

Syntax:

JSON.stringify(value, replacer, space)

Let's specify the number of spaces in the example above. See below:

const skill = {
  lang: 'JavaScript'
};

const occupation = {
  title: 'Junior software engineer',
  employees: [{name: "Bob"}, {name: "James"}],
  habbit: skill // occupation references skill
};

skill.work = occupation; // skill references occupation

const replacer = (key, value) => {
  console.log(`${key}: ${value}`);
  return (key == 'work') ? undefined : value;
}

console.log( JSON.stringify(occupation, replacer) );

/*
: [object Object]
title: "Junior software engineer",
employees: [object Object],[object Object]
0: [object Object]
name: Bob
1: [object Object]
name: James
habbit: [object Object]
lang: JavaScript
work: [object Object]
{
  "title": 'Junior software engineer',
  "employees": [
    {
      "name": "Bob"
    },
    {
      "name": "James"
    }
  ],
  "habbit": {
    "lang": "JavaScript"
  }
}
*/

The third argument can also be a string. See below:

console.log( JSON.stringify(occupation, replacer, '--') );

/*
: [object Object]
title: "Junior software engineer",
employees: [object Object],[object Object]
0: [object Object]
name: Bob
1: [object Object]
name: James
habbit: [object Object]
lang: JavaScript
work: [object Object]
{
--"title": "Junior software engineer",
--"employees": [
----{
------"name": "Bob"
----},
----{
------"name": "James"
----}
--],
--"habbit": {
----"lang": "JavaScript"
--}
}
*/

toJSON

The toJSON converts a type (object) to JSON.

See the examples below:

without toJSON function

const skill = {
  lang: 'JavaScript'
};

const occupation = {
  title: 'Junior software engineer',
  skill
};

console.log( JSON.stringify(occupation) );
// {"title":"Junior software engineer","skill":{"lang":"JavaScript"}}

with toJSON function

const skill = {
  lang: 'JavaScript',
  toJSON() {
    return this.lang;
  }
};

const occupation = {
  title: 'Junior software engineer',
  skill
};

console.log( JSON.stringify(skill) ); // "JavaScript"
console.log( JSON.stringify(occupation) );
// {"title":"Junior software engineer","skill":{"lang":"JavaScript"}}

The toJSON method mainly is used to convert a Date object into a string - YYYY-MM-DDTHH:mm:ss.sssZ.

See the example below:

const dataStr() {
  let date = new Date();
  let dateJson = date.toJSON();
  console.log(dateJson );
}

dataStr(); // 'YYYY-MM-DDTHH:mm:ss.sssZ'

Buy me a Coffee


JavaScript

Part 1 of 50

You will learn the basics of JavaScript, including the Modern JS or *ECMAScript 2015+* The approach is from the basics to more advanced topics with lots of examples. It also include YouTube videos...