I am trying to convert a json to object and access the attribute values in typescript. I have tried chatgpt but the answer from that is static considering there are only 2 games i.e game1 and game2. How can I convert it into class object considering there can be multiple games.
{
"defaultConfiguration": {
"listedGames": {
"game1": {
"Id": 1,
"contentPartnerSplit": {
"partner1": 50,
"partner2": 50
},
"regionalSplit": {
"region1": 50,
"region2": 20,
"region3": 30
}
},
"game2": {
"Id": 2,
"contentPartnerSplit": {
"partner1": 30,
"partner2": 70
},
"regionalSplit": {
"region1": 50,
"region2": 50
}
}
.
.
.
}
}
}
Below is what I tried
export class GamesConfig {
defaultConfiguration?: {
listedGames?: {
games?: Map<string, Games>;
}
};
}
export class Games {
Id: string;
regionalSplit: RegionalSplit;
contentPartnerSplit: ContentPartnerSplit;
}
But when I try to parse json and access attribute Id I get undefined
const jsonObj = JSON.parse(config)
jsonObj.defaultConfiguration?.listedGames?.games?.get('game1')?.Id
JSON.parseto magically instantiate your classesMaps butRecords. There's no such thing as.get()onRecords, thus you must access it via['game1']. Second, you're accessinglistedGames?.games?, which does not exist in the provided json, that's why you receiveundefinedeventually. Instead, the games are directly within thelistedGamesproperty (listedGames?: Record<string, Game>;). To properly access theIdattribute of "game1", you'd usejsonObj.defaultConfiguration?.listedGames?.['game1']?.Id.