Is there something like object.toJSON in ES6?

10,974

You can use JSON.stringify and pass any kind of variable to it (given that it can be represented in JSON).

It works in all current browsers; in case you need a fallback for a really old browser, you can use Crockford's JSON-js.

However, keep in mind that, regarding objects, only public properties are serialized. There's no a generic way to serialize function variables etc. on the fly.

This is why some special object types provide a toJSON or similar method. In order to use such a function for arbitrary objects, you must pass a function as second parameter to JSON.stringify which checks for the existence of a toJSON function.

For example, the following should work (not tested, just from the top of my mind):

var jsonString = JSON.stringify(someLargeObject, function(key, value){
    return (value && typeof value.toJSON === 'function') 
        ? value.toJSON()
        : JSON.stringify(value);
});

If your someLargeObject contains a sub-object with a toJSON method, this code would use the object's implementation, otherwise use JSON.stringify.

Share:
10,974
Hedge
Author by

Hedge

Updated on June 22, 2022

Comments

  • Hedge
    Hedge almost 2 years

    I'm using ES6 I transpile using Babel into ordinary JavaScript.

    I want to serialise objects into JSON format and am wondering if ES5,ES6 offers a convenient function to do so.

    For Maps and Sets there is a toJSON()-function proposed in ES7