l’ve got an object that I need to use in a Webhook and am curious if anyone has a code snippet or something clever they’ve done with regards to generating a JSON representation of the object? There are enough properties, etc. that it will be a bit tedious to go through and map each one individually.
Assuming you just want to get a JSON representation of the properties of an object (ignoring links, etc.), you can do something like the following:
@Function()
public getAircraftObjectJson(aircraft: Aircraft): string {
const keys = this.getKeys(Aircraft.properties); // ["manufacturer", "model", "capacity", "registration"]
// you could do this more cleanly, for example with lodash
const obj: { [key: string]: any } = {}
keys.forEach(key => {
obj[key] = aircraft[key];
});
return JSON.stringify(obj);
}
private getKeys<ObjectType extends object>(obj: ObjectType): Array<keyof ObjectType> {
return Object.keys(obj) as Array<keyof ObjectType>
}
Note that this will only capture the properties on the Aircraft object when the Function was published. So any properties added after the fact would be omitted from the JSON and you would need to republish the Function to fix that.
1 Like
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.