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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more