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 blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay