Modify JSON.stringify() for specific components

Viewed 69

I have a React component state that holds many different classes that needs to be stringify()'d. Most of the components need to be specially treated before they can be put into the JSON object. I believe that using the replacer() and if statements to check the type and then modify the output would be too cumbersome. Short of creating a custom parsing system, is there a way to customize the stringify() in what it parses?

The idea would be to have a custom function (toString() for example) in each class that when the parser reaches the class, instead of going through the key-value pairs, would call the function and append it to the JSON object.

1 Answers

From JSON.stringify description If the value has a toJSON() method, it's responsible to define what data will be serialized.

Usage

JSON.stringify({ toJSON() {return {a: 'eureka'}}})
Related