Andrii Romanchak
Andrii Romanchak

Reputation: 778

JSON.stringify() - object's custom serializer

Let's say I have an object:

const a = {
  foo: 123,
  bar: 'example'
}

This object is a part of many other objects i.e.

const b = {
  a: a,
  anotherField: "example"
}

Actually, I'm using TypeScript and all these objects are of the same class which I believe isn't important.

After serializing the b object to JSON I need to get this string (i.e. I just get the foo field from a):

{ a: 123, anotherField: "example" }

What is the easiest and most elegant way to tell JSON.stringify() how to convert the a object to a string?

Probably something similar to what Python allows.

Upvotes: 11

Views: 7773

Answers (2)

mjk
mjk

Reputation: 386

You could define toJSON in a.

If an object being stringified has a property named toJSON whose value is a function, then the toJSON() method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON() method when called will be serialized.

(source: MDN)

For example:

class A {
  constructor(foo, bar) {
    this.foo = foo;
    this.bar = bar;
  }

  toJSON() {
    return this.foo;
  }
}

const a = new A(123, "some name");
const b = {
  a: a,
  anotherField: "example"
};

console.log(JSON.stringify(b)); // "{"a":123,"anotherField":"example"}"

Upvotes: 27

Jonas Wilms
Jonas Wilms

Reputation: 138307

You could use the replacer while stringifying:

 const result = JSON.stringify(b, (k, v) => v && v.stringify() || v);

That way you can easily add a custom stringification to a:

 const a = {
   foo: 123,
   bar: 'example',
   stringify() { return this.foo; }
 }

Upvotes: 7

Related Questions