# JS Tip of the Day: Custom Serialization With toJSON

**URL:** <https://forum.kirupa.com/t/js-tip-of-the-day-custom-serialization-with-tojson/643071>\
**Category:** web dev\
**Created:** [June 3, 2020, 2:30pm UTC](https://forum.kirupa.com/t/js-tip-of-the-day-custom-serialization-with-tojson/643071 "2020-06-03T14:30:37Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![senocular](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/senocular/32/7217_2.png) [@senocular](https://forum.kirupa.com/u/senocular)\
**Post date:** [June 3, 2020, 2:30pm UTC](https://forum.kirupa.com/t/js-tip-of-the-day-custom-serialization-with-tojson/643071/1 "2020-06-03T14:30:37Z")

</div>

**Custom Serialization With toJSON**  
Level: Intermediate

Just like Objects have their own `toString()` method for determining how they’re converted (most of the time) to strings, they too can have a `toJSON()` method for determining how they’re converted into JSON. If present, the `toJSON()` method is called when the object is converted to a JSON string via `JSON.stringify()`.

Though used to create a JSON string, `toJSON()` is actually expected to return an object. It is that returned object that is then run through the stringify process and used to represent the current object in the JSON string.

```javascript
let normal = { prop: 1 };
let special = {
    prop: 1,
    toJSON() {
        return { jsonProp: 2 };
    }
};

console.log(JSON.stringify(normal)); // {"prop": 1}
console.log(JSON.stringify(special)); // {"jsonProp": 2}

```

When called, `toJSON()` will receive a single argument which is the key of the object being converted.

```javascript
let parent = {
    child: {
        prop: 1,
        toJSON(key) {
            return { [key]: 'is my key' };
        }
    }
};
console.log(JSON.stringify(parent));
// {"child":{"child":"is my key"}}

```

If the object is the same object is passed into `toJSON()` the key will be an empty string (`""`). Be careful, however, since empty strings are also valid property keys. So when `key` is an empty string, it is not also a guarantee that the object was the same object given to `toJSON()`.

Unlike `toString()`, most objects do not implement this method and instead leave it to the default behavior of `JSON.stringify()` to convert them. The only exception in the core API is, probably not surprisingly by now, Date. The Date object has its own `toJSON()` which converts date objects into strings based on the return value of `toISOString()`.

```javascript
let date = new Date(1979, 0);
console.log(date.toJSON()); // 1979-01-01T05:00:00.000Z
console.log(date.toISOString()); // 1979-01-01T05:00:00.000Z

```

More info:

- [toJSON on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON_behavior)

* * *

More tips: [JavaScript Tips of the Day](http://forum.kirupa.com/t/javascript-tips-of-the-day/641803/1)
