【发布时间】: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。
来自代码的日志:
是什么导致了这个问题,我该如何解决?
【问题讨论】:
-
在您报告的代码中,没有导致屏幕截图出现问题的
console.log -
如果您无法在 stackblitz 中重现该问题,则说明情况有所不同,您应该隔离该差异。由于您在此处的代码不构成minimal reproducible example,因此人们只能猜测。我的猜测:你不知道
console.logon an object value might show you a "live" version of the object and not the state of the object as it was when you logged it -
请添加一个显示实际问题的minimal reproducible example,因为这完全符合预期:jsfiddle.net/9zft31jq
-
自定义不是Json格式,你可以试试这个:
custom = '{"Tickets":{"reservation":true,"price":10,"section":null,"row":10,"seat":10,"event":5,"id":1,"created":"2019-06-14T14:16:17.144Z"}}'; -
我在 JavaScript 上尝试了两种变体,并且都有效,我认为这是 angular 的问题。
标签: json typescript parsing es6-map