DEV Community

Jan Küster
Jan Küster

Posted on • Updated on


How stringify Proxy to JSON

If you ever had to deal with a Proxy then you might come to the point where you need to stringify their returned values.

Fortunately, the JSON implementation in ECMA Script allows to define a custom toJSON method on Objects. A good built-in example is Date.prototype.toJson. With toJSON you can fine-tune what exactly will be part of the stringified Object.

On a Proxy you might want to have direct access to the underlying Object and rather define your custom JSON in a get trap.

The following example solves this easily:

const personProxy = new Proxy({}, {
  get: function (target, key) {
    if (key === 'toJSON') {
      return () => ({ name: 'bar' })

    if (key === 'name') return 'foo'
Enter fullscreen mode Exit fullscreen mode

If you directly call the name value on the proxy, it will return name.

However, when passing the Proxy instance to JSON.stringify it will try to call toJSON on the Proxy. Since our get trap handles toJSON as function, the stringify implementation can actually call it as if it would be a member function.

console.log('name', { name: })  // "name" "{ name: 'foo' }"
console.log('json', JSON.stringify(personProxy)) // "json" "{'name':'bar'}"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

11 Tips That Make You a Better Typescript Programmer


1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!