JavaScript JSON and toJSON Methods
Tags: webdev, codenewbie, javascript, tutorial
Published: 2021-03-20 18:25:26

[![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1616331324721/GSjZnVC3o.png)](https://paykstrt.com/2073/70457)

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

```js
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":[{},{}]}
```

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:

```js
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"}}
```

#### *replacer* as an function

The `replacer` can be used as a function.

Syntax:

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

See the example below:

```js
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"}}
*/
```

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:

```js
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"
  }
}
*/
```

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

```js
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"
--}
}
*/
```

---
### toJSON

The `toJSON` converts a type (object) to JSON.

See the examples below:

**without `toJSON` function**
```js
const skill = {
  lang: 'JavaScript'
};

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

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

**with `toJSON` function**
```js
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"}}
```

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

See the example below:

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

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

**Happy coding!!!**

---
[![Buy me a Coffee](https://res.cloudinary.com/bizstak/image/upload/v1610317510/ko-fi-trans_fr3su4.png)](https://www.buymeacoffee.com/techstackmedia)

---
[![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1616331324721/GSjZnVC3o.png)](https://paykstrt.com/2073/70457)