Using JSON.stringify in combination with TypeScript getter / setter

I am using getter / setter assemblers in TypeScript. Since it is impossible to have the same name for a variable and a method, I started the variable prefix with a lower dash, as was done in many examples:

private _major: number; get major(): number { return this._major; } set major(major: number) { this._major = major; } 

Now, when I use the JSON.stringify () method to convert the object to a JSON string, it will use the variable name as the key: _major.

As I don’t want the JSON file to have all the keys prefixed with a lower dash, is it possible to make TypeScript use the getter method name, if available? Or are there other ways to use getter / setter methods, but still produce pure JSON output?

I know that there are ways to manually modify the JSON keys before they are written to the output of the string. I am curious if there is a simpler solution.

Here is a JSFiddle that demonstrates the current behavior.

+9
source share
4 answers

No, you cannot have JSON.stringify using the receiver / setter name instead of the property name.

But you can do something like this:

 class Version { private _major: number; get major(): number { return this._major; } set major(major: number) { this._major = major; } toJsonString(): string { let json = JSON.stringify(this); Object.keys(this).filter(key => key[0] === "_").forEach(key => { json = json.replace(key, key.substring(1)); }); return json; } } let version = new Version(); version.major = 2; console.log(version.toJsonString()); // {"major":2} 
+3
source

based on @ Jan-Aagaard solution. I tested this

 public toJSON(): string { let obj = Object.assign(this); let keys = Object.keys(this.constructor.prototype); obj.toJSON = undefined; return JSON.stringify(obj, keys); } 

to use the toJSON method

+7
source

I think iterating through properties and manipulating a string is dangerous. I would do using a prototype of the object itself, something like this:

 public static toJSONString() : string { return JSON.stringify(this, Object.keys(this.constructor.prototype)); // this is version class } 
+2
source

I wrote a small ts-typed library that generates getter / setter for typing purposes at runtime. I ran into the same problem when using JSON.stringify (). So I solved this by adding some serializer and offering to implement a kind of toString (in Java), calling it toJSON.

Here is an example:

 import { TypedSerializer } from 'ts-typed'; export class RuntimeTypedClass { private _major: number; get major(): number { return this._major; } set major(major: number) { this._major = major; } /** * toString equivalent, allows you to remove the _ prefix from props. * */ toJSON(): RuntimeTypedClass { return TypedSerializer.serialize(this); } } 
0
source

All Articles