res.json返回无意修改的input

我的res.json函数似乎在修改我的数据。 如果我在函数中logging数据,它将返回正确的数据。 只有在res.json里面我的数据改变了,我不知道为什么。

例如。 它返回{"unix":"1484600306","naturalFormat":"2017-01-16"}它返回{"unix":"1484600306","naturalFormat":"\"2017-01-16\""}.

function:

 function unixToDate(timestamp) { var a = new Date(timestamp * 1000); //console.log(a); var rgx = /T(\d{2}):(\d{2}):(\d{2}).(\d{3})Z/; var newA = JSON.stringify(a); //console.log(newA.replace(rgx, "")); return newA.replace(rgx, ""); } 

路线

 router.get('/:unix', function(req, res) { var timestamp = req.params.unix; var regex = new RegExp("\\d{10}"); if (regex.test(timestamp)) { var date = unixToDate(timestamp); console.log(date); res.json({ unix : timestamp, naturalFormat : date }); } else { res.json({ unix: null, naturalFormat : null}); } }); 

再一次,我是一个正则expression式的新手,如果我不得不猜测它会与这个有关。

PS我没有使用toString(),因为我的date出来错了,即2015年11月30日而不是2015年12月1日,所以这就是为什么我这样做与正则expression式。

谢谢!

问题在于unixToDate ,在这里:

 var newA = JSON.stringify(a); 

您将序列化为JSON的date,这意味着newA将是这样一个string: "2017-01-16T00:00:000.000Z"包括引号。 然后,当你调用res.json ,它将再次序列化该string,引号和全部。

最简单的解决方法是使用Date.prototype.toISOString来代替。 它将返回与上面相同的string,不带引号:

 var newA = a.toISOString(); 

事实上,用String.prototype.replace去除date部分的方法有点复杂。 ISO 8601date在每个位置总是有相同数量的数字,所以为什么不使用String.prototype.slice

 function unixToDate(timestamp) { var date = new Date(timestamp * 1000); return date.toISOString().slice(0, 10); }