Skip to content

Instantly share code, notes, and snippets.

@SCP002
Last active April 7, 2021 20:25
Show Gist options
  • Save SCP002/037892a32da8178f546205147d4b8644 to your computer and use it in GitHub Desktop.
Save SCP002/037892a32da8178f546205147d4b8644 to your computer and use it in GitHub Desktop.
TypeScript: Parse & Stringify partially known / dynamic JSON. Using classes (type safe).
// npm install --save-dev class-transformer
import 'reflect-metadata';
import { classToPlain, deserialize, Exclude, Type } from 'class-transformer';
const inpJsonStr: string = `
{
"topKnownKey": 1,
"topUnknownKey": 2,
"nestedKnownArray": [
{
"nestedKnownKey": 3,
"nestedUnknownKey": 4
},
{
"nestedKnownKey": 5,
"nestedUnknownKey": 6
}
],
"nestedUnknownArray": [
{
"nestedKnownKey": 7,
"nestedUnknownKey": 8
}
]
}
`;
export class Top {
topKnownKey!: number;
@Type(() => NestedKnownArray) nestedKnownArray!: NestedKnownArray[];
@Exclude() excludedKnownKey!: number; // Field sample for internal needs, excluded from JSON processing.
}
export class NestedKnownArray {
nestedKnownKey!: number;
@Exclude() excludedKnownKey!: number; // Field sample for internal needs, excluded from JSON processing.
}
// Decode.
const top: Top = deserialize(Top, inpJsonStr);
// Modify.
top.topKnownKey = 100;
top.excludedKnownKey = 200;
top.nestedKnownArray[0].nestedKnownKey = 300;
top.nestedKnownArray[0].excludedKnownKey = 400;
// Encode.
const outJsonObj: Object = classToPlain(top);
const outJsonStr: string = JSON.stringify(outJsonObj, null, 2);
// Print output.
console.log(outJsonStr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment