强制JSON.stringify转义正斜杠(即`\/`) [英] Force JSON.stringify to escape forward slash (i.e. `\/`)
问题描述
我正在用nodejs
编写服务,以替换用.NET
编写的现有系统.该服务提供了JSON API,其中一个调用返回一个日期. JSON的Microsoft日期格式为/是,其中1599890827000
是毫秒偏移量:
I'm writing a service in nodejs
that replaces an existing system written in .NET
. The service provides a JSON API, one of the calls returns a date. The Microsoft date format for JSON was/is where 1599890827000
is the milliseconds offset:
/Date(1599890827000)/
我遇到的问题是JSON.stringify
(在res.send
和res.json
在express
中使用)不能逃脱正斜杠,而是现有的Microsoft库(
The problem I am having is that JSON.stringify
(used in res.send
and res.json
in express
) does not escape forward slashes but the existing Microsoft library (System.Web.Script.Serialization.JavaScriptSerializer) expects forward slashes to be escaped.
例如,客户端期望这样的JSON:
For example, the client expects JSON like this:
{
"Expires": "\/Date(1599890827000)\/"
}
但是JSON.stringify
会产生以下内容:
{
"Expires": "/Date(1599890827000)/"
}
第二个结果是完全有效的,但是Microsoft库不喜欢它并且无法解析.
The second result is perfectly valid but the Microsoft library doesn't like it and fails to parse.
有什么方法可以强制Express/Node/JSON在JSON.stringify
中转义正斜杠或处理这种情况?
Is there any way I can force Express/Node/JSON to escape forward slashes in JSON.stringify
or handle this case?
我可以在运行stringify
之后使用正则表达式替换,但是由于我们在项目中使用了对象缓存系统,因此在发送给客户端之前必须先转换为JSON,而不是让它使用.
I could use a regex replacement after running stringify
but because of an object caching system we use in the project it would be very hacky to have to convert to JSON before sending to the client instead of letting.
注意:我不能更改客户端,只能更改api服务.
Note: I cannot change the client, only the api service.