How stringify Proxy to JSON

jankapunkt

Jan Küster

Posted on November 2, 2020

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: personProxy.name })  // "name" "{ name: 'foo' }"
console.log('json', JSON.stringify(personProxy)) // "json" "{'name':'bar'}"
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
jankapunkt
Jan Küster

Posted on November 2, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How stringify Proxy to JSON
javascript How stringify Proxy to JSON

November 2, 2020