I'm facing a challenge in importing JSON data that may include mappings which could be either present or absent within one of the properties. I initially thought that using Map<string, number>
as the correct data type to represent this scenario would work, but unfortunately, I encounter an error when attempting to do so.
The structure of my JSON file, named data.json, is shown below:
{
"datas": [
{
"name":"test1",
"config":"origin",
"entries": {
"red":1,
"green":2
}
},
{
"name":"test2",
"config":"remote",
"entries": {
"red":1,
"blue":3
}
},
{
"name":"test3",
"entries": {
"red":1,
"blue":3,
"purple":3
}
}
]
}
The TypeScript code in Data.ts responsible for reading this data appears like this:
import data from './data.json';
export class Data {
public name:string;
public config:string;
public entries:Map<string, number>;
constructor(
name:string,
entries:Map<string, number>,
config?:string
) {
this.name = name;
this.entries = entries;
this.config = config ?? "origin";
}
}
export class DataManager {
public datas:Data[] = data.datas;
}
However, the final line,
public datas:Data[] = data.datas;
, ends up causing an error.
This raises the question - what is the proper way to import such data?
The main objectives here are threefold:
- Any time
entries
is present, it should undergo some form of validation to ensure it only consists of properties of typenumber
. The specific properties remain unknown to the programmer, but will be significant to the end user. - If
config
is missing in the JSON file, the creation ofData
objects should default to a preset value (in this case, "origin") - The process of assigning the data must be streamlined and free of unnecessary boilerplate code. In the event that
Data
gains a new property in the future (and there may or may not be corresponding updates to the data within Data.json), there shouldn't be a need to alter howDataManager.data
fetches the values
Is this feasible, and if so, what is the right approach to writing code that achieves these objectives?