12

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.

2
  • 1
    Definitely, you have another problem because the JSON.stringify will convert to string that js object. Commented Oct 19, 2018 at 15:25
  • 2
    Actually, none. JSON.stringify just converts the object to a JSON-compliant string, you can transform the object before serializing it. It's not really language-related, it's just a bad design, in this case, in my opinion. Commented Oct 19, 2018 at 15:25

2 Answers 2

29

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"}"

Sign up to request clarification or add additional context in comments.

Comments

7

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; }
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.