DEV Community

Cover image for JavaScript JSON and toJSON Methods
Bello Osagie
Bello Osagie

Posted on • Edited on

JavaScript JSON and toJSON Methods

image.png


The JSON.stringify syntax used so far is:

JSON.stringify(value)
Enter fullscreen mode Exit fullscreen mode

The general syntax actually is:

JSON.stringify(value[, replacer, space])
Enter fullscreen mode Exit fullscreen mode
  • replacer and space are optional.

replacer

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

JSON.stringify(value, replacer)
Enter fullscreen mode Exit fullscreen mode

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, [ ... ])
Enter fullscreen mode Exit fullscreen mode

See the example below:

const skill = {
  lang: 'JavaScript'
};

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

skill.work = occupation; // skill references occupation

console.log( JSON.stringify(occupation, ['level', 'employees']) );
// {"level":"Junior software engineer","employees":[{},{}]}
Enter fullscreen mode Exit fullscreen mode

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 = {
  level: 'Junior software engineer',
  employees: [ {name: "Bob"}, {name: "James"} ],
  habbit: skill // occupation references skill
};

skill.work = occupation; // skill references occupation

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

replacer as an function

The replacer can be used as a function.

Syntax:

JSON.stringify(value, function(key, value))
Enter fullscreen mode Exit fullscreen mode

See the example below:

const skill = {
  lang: 'JavaScript'
};

const occupation = {
  level: '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]
level: "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]
{"level":"Junior software engineer","employees":[{"name":"Bob"},{"name":"James"}],"habbit":{"lang":"JavaScript"}}
*/
Enter fullscreen mode Exit fullscreen mode

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

For example

...
employees: [object Object],[object Object]
...
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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

const skill = {
  lang: 'JavaScript'
};

const occupation = {
  level: '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]
level: "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]
{
  "level": 'Junior software engineer',
  "employees": [
    {
      "name": "Bob"
    },
    {
      "name": "James"
    }
  ],
  "habbit": {
    "lang": "JavaScript"
  }
}
*/
Enter fullscreen mode Exit fullscreen mode

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

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

/*
: [object Object]
level: "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]
{
--"level": "Junior software engineer",
--"employees": [
----{
------"name": "Bob"
----},
----{
------"name": "James"
----}
--],
--"habbit": {
----"lang": "JavaScript"
--}
}
*/
Enter fullscreen mode Exit fullscreen mode

toJSON

The toJSON converts a type (object) to JSON.

See the examples below:

without toJSON function

const skill = {
  lang: 'JavaScript'
};

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

console.log( JSON.stringify(occupation) );
// {"level":"Junior software engineer","skill":{"lang":"JavaScript"}}
Enter fullscreen mode Exit fullscreen mode

with toJSON function

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

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

console.log( JSON.stringify(skill) ); // "JavaScript"
console.log( JSON.stringify(occupation) );
// {"level":"Junior software engineer","skill":{"lang":"JavaScript"}}
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

Happy coding!!!


Buy me a Coffee


image.png

Top comments (0)