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.
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.
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.
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.
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"}"
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With