【问题标题】:JSON.parse() output changes if assigned to a variable如果分配给变量,JSON.parse() 输出会发生变化
【发布时间】:2019-10-29 05:36:47
【问题描述】:

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

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)); 这里的输出是wearg id = 0, row = null, seat = null。

来自代码的日志:

是什么导致了这个问题,我该如何解决?

【问题讨论】:

标签: json typescript parsing es6-map


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多