简体   繁体   中英

From JS Object to JSON Angular

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM