Reputation: 3202
Consider the following TypeScript class:
export class Spot {
public flight:number;
public dateAndTimes:Map<string,string>
public unitCost:number;
constructor(){
this.flight=0;
this.dateAndTimes= new Map<string,string>();
this.unitCost=0;
}
}
How can I convert the Spot object to JSON?
I try JSON.stringify(spot)
, but the attribute dateAndTimes
it's serialized as empty... for example:
"spot": {
'flight':2,
{},
'unitCost':3500
}
Thank you very much!
Upvotes: 0
Views: 150
Reputation: 10909
Quoting from the MDN documentation for JSON.stringify
:
- All the other Object instances (including Map, Set, WeakMap, and WeakSet) will have only their enumerable properties serialized.
As a Map
can have any type for keys and values then even if you were able to stringify it the JSON spec does not account for any types outside of "objects, arrays, numbers, strings, booleans, and null". Therefore if any of the keys or values of the Map
are not of those types then it would not be allowed by the specification.
That last point is extremely important as even if a Map was somehow serialized to JSON but included any type of key or value not of the aforementioned allowed types then it is not determinable how a parser would process the resultant JSON back into an object. If it is not necessary to use a Map then I would recommend using a plain object for this to avoid this issue completely.
Note that it is also not possible to roll your own replacer
function for the JSON.stringify
method to handle that functionality.
Upvotes: 1