DEV Community

Jan Küster 🔥
Jan Küster 🔥

Posted on • Edited on

3

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay