简体   繁体   English

强制JSON.stringify转义正斜杠(即`\ /`)

[英]Force JSON.stringify to escape forward slash (i.e. `\/`)

I'm writing a service in nodejs that replaces an existing system written in .NET . 我正在用nodejs编写一个服务来替换用.NET编写的现有系统。 The service provides a JSON API, one of the calls returns a date. 该服务提供了一个JSON API,其中一个调用返回一个日期。 The Microsoft date format for JSON was/is where 1599890827000 is the milliseconds offset: JSON的Microsoft日期格式是/,其中1599890827000是毫秒偏移量:

/Date(1599890827000)/

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.stringify (在express使用res.sendres.json )不会转义正斜杠但现有的Microsoft库( System.Web.Script.Serialization.JavaScriptSerializer )期望转义斜杠被转义。

For example, the client expects JSON like this: 例如,客户端期望JSON像这样:

{
  "Expires": "\/Date(1599890827000)\/"
}

But JSON.stringify produces the following: 但是JSON.stringify产生以下内容:

{
  "Expires": "/Date(1599890827000)/"
}

The second result is perfectly valid but the Microsoft library doesn't like it and fails to parse. 第二个结果完全有效,但Microsoft库不喜欢它并且无法解析。

Is there any way I can force Express/Node/JSON to escape forward slashes in JSON.stringify or handle this case? 有什么办法可以强制Express / Node / JSON在JSON.stringify转义正斜杠或处理这种情况吗?

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. 我可以在运行stringify后使用正则表达式替换,但由于我们在项目中使用的对象缓存系统,在发送到客户端而不是让它之前必须转换为JSON是非常hacky。

Note: I cannot change the client, only the api service. 注意:我无法更改客户端,只能更改api服务。

Replacer happens before escaping , leaving you with either: 在逃离之前发生替换,留下以下任何一种:

"/Date(1599890827000)/"

Or: 要么:

"\\/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: 这意味着您将无法使用Express内置的res.json(data) ,可能需要编写一个函数来替换它,如:

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, '\\/'));
}

Calling it as: 将其称为:

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

However , that said, fixing the behaviour in .NET would be the more forward compatible solution. 但是 ,这就是说,修复.NET中的行为将是更具前瞻性的解决方案。

Use replacer parameter 使用replacer参数

function replaceSlashes(key, value) 
{
  if ( typeof value == "string")
  {
    value = value.replace(/\//g, "\\/");
  }
  return value;
}

var jsonString = JSON.stringify(jsonString, replaceSlashes);

It will still produce a double backward slash since stringify method by itself won't product a single slash without escaping the same.\\ 它仍会产生双反斜杠,因为stringify方法本身不会产生单斜杠而不会转义相同的斜杠。

You need to try something like this 你需要尝试这样的事情

JSON.stringify({
  "Expires": "\/Date(1599890827000)\/"
}, replaceSlashes).replace(/\\\\/g, "\\");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM