如果分配给变量,JSON.parse()输出将更改

时间:2019-06-14 14:51:34

标签: json typescript parsing es6-map

我正在开发一个可以购买活动门票的网站。选择票证后,它就在购物车中。我有一个sessionService.ts,基本上是一个Map<string, any>,可以从本地存储读取/写入本地存储。将地图存储为JSON字符串效果很好,但是当我从存储中加载数据并尝试将JSON字符串解析到Map时,数据就不再一致了。

console.log(JSON.parse(data))显示正确的值,而let x = JSON.parse(data); console.log(x);显示操纵的数据。

我尝试在Stackblitz上重新创建问题,但是我无法做到这一点。


export class Ticket {
  public id: number;
  public created: Date;

  constructor(
    public reservation: boolean,
    public price: number,
    public section: number,
    public row: number,
    public seat: number,
    public event: number | Event) {
  }
}

private testParsing(){
    const custom = '[["Tickets",[{"reservation":true,"price":10,"section":null,"row":10,"seat":10,"event":5,"id":1,"created":"2019-06-14T14:16:17.144Z"}]]]';
    console.log('String to parse: ', custom);
    console.log('String parsed directly to console: ', JSON.parse(custom));
}

console.log('String to parse: ', custom);将显示正确的值。

console.log('String parsed directly to console: ', JSON.parse(custom));,这里的输出已磨损:id = 0,row = null,seat = null。

来自代码https://imgur.com/a/BumYqkI

的日志

什么原因导致此问题,我该如何解决?

1 个答案:

答案 0 :(得分:0)

问题在于它是一个嵌套结构,尝试使用JSON.parse(JSON.stringify(custom))应该会得到相同的结果。我能够在控制台中重现您的问题并使用此方法解决。