强制JSON.stringify转义正斜杠(即`\/`) [英] Force JSON.stringify to escape forward slash (i.e. `\/`)

查看:1381
本文介绍了强制JSON.stringify转义正斜杠(即`\/`)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用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.sendres.jsonexpress中使用)不能逃脱正斜杠,而是现有的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.

推荐答案

或者:

"\\/Date(1599890827000)\\/"

实际上,您将不得不在结果输出上运行字符串替换:

Realistically you will have to run a string replace on the resulting output:

JSON.stringify(data).replace(/\//g, '\\/');

这意味着您将无法使用

This means that you won't be able to use the express built in res.json(data) and may need to instead write a function to replace it like:

function dotNetJSONResponse(res, data) {

    var app = res.app;
    var replacer = app.get('json replacer');
    var spaces = app.get('json spaces');
    var body = JSON.stringify(data, replacer, spaces);

    if (!this.get('Content-Type')) {
        res.set('Content-Type', 'application/json');
    }

    return res.send(body.replace(/\//g, '\\/'));
}

称呼为:

app.get('/url', function (req, res) {
     dotNetJSONResponse(res, data);
});

但是,也就是说,修复.NET中的行为将是更向前兼容的解决方案.

However, that said, fixing the behaviour in .NET would be the more forward compatible solution.

这篇关于强制JSON.stringify转义正斜杠(即`\/`)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆