Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 351
Andrii Romanchak Avatar asked Oct 19 '18 15:10

Andrii Romanchak


People also ask

Can you JSON Stringify an object?

The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

When should I use JSON Stringify?

The JSON. stringify() method in Javascript is used to create a JSON string out of it. While developing an application using JavaScript, many times it is needed to serialize the data to strings for storing the data into a database or for sending the data to an API or web server.

What is difference between Stringify and serialize?

stringify() ignores functions/methods when serializing. JSON also can't encode circular references. Most other serialization formats have this limitation as well but since JSON looks like javascript syntax some people assume it can do what javascript object literals can. It can't.


2 Answers

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"}"
like image 71
mjk Avatar answered Nov 09 '22 04:11

mjk


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; }
 }
like image 28
Jonas Wilms Avatar answered Nov 09 '22 05:11

Jonas Wilms