我必须形成一个JSON字符串,其中一个值有新的行字符。这必须转义,然后使用AJAX调用发布。谁能建议一种用JavaScript转义字符串的方法?我没有使用jQuery。


当前回答

EDIT: Check if the api you’re interacting with is set to Content-Type: application/json, &/or if your client http library is both stringify-ing and parsing the http request body behind the scenes. My client library was generated by swagger, and was the reason I needed to apply these hacks, as the client library was stringifying my pre-stringified body (body: “jsonString”, instead of body: { ...normal payload }). All I had to do was change the api to Content-Type: text/plain, which removed the JSON stringify/parsing on that route, and then none of these hacks were needed. You can also change only the "consumes" or "produces" portion of the api, see here.

原文:如果你的谷歌一直登陆你这里,你的api抛出错误,除非你的JSON双引号转义("{\"foo\": true}"),所有你需要做的是stringify两次,例如JSON.stringify(JSON.stringify(bar)))

其他回答

在使用任何形式的Ajax时,Web上似乎缺乏关于从CGI服务器接收到的响应格式的详细文档。这里的一些条目指出,必须转义返回文本或json数据中的换行符,以防止json转换中的无限循环(挂起)(可能是通过抛出未捕获的异常创建的),无论是由jQuery自动完成还是使用Javascript系统或库json解析调用手动完成。

In each case where programmers post this problem, inadequate solutions are presented (most often replacing \n by \\n on the sending side) and the matter is dropped. Their inadequacy is revealed when passing string values that accidentally embed control escape sequences, such as Windows pathnames. An example is "C:\Chris\Roberts.php", which contains the control characters ^c and ^r, which can cause JSON conversion of the string {"file":"C:\Chris\Roberts.php"} to loop forever. One way of generating such values is deliberately to attempt to pass PHP warning and error messages from server to client, a reasonable idea.

根据定义,Ajax在幕后使用HTTP连接。这样的连接使用GET和POST传递数据,这两者都需要对发送的数据进行编码,以避免错误的语法,包括控制字符。

这给了构造解决方案的足够提示(它需要更多的测试):在PHP(发送)端使用rawurlencode来编码数据,在Javascript(接收)端使用unescape来解码数据。在某些情况下,您将把它们应用于整个文本字符串,在其他情况下,您将只应用于JSON中的值。

如果这个想法被证明是正确的,那么可以构造一些简单的例子来帮助各个级别的程序员一劳永逸地解决这个问题。

最好使用JSON.parse(yourUnescapedJson);

在JSON.stringify上还有第二个参数。所以,更优雅的解决方案是:

function escape (key, val) {
    if (typeof(val)!="string") return val;
    return val
      .replace(/[\"]/g, '\\"')
      .replace(/[\\]/g, '\\\\')
      .replace(/[\/]/g, '\\/')
      .replace(/[\b]/g, '\\b')
      .replace(/[\f]/g, '\\f')
      .replace(/[\n]/g, '\\n')
      .replace(/[\r]/g, '\\r')
      .replace(/[\t]/g, '\\t')
    ; 
}

var myJSONString = JSON.stringify(myJSON,escape);

使用encodeURIComponent()对字符串进行编码。

例如。var myEscapedJSONString = encodeURIComponent(JSON.stringify(myJSON));

你不需要解码它,因为web服务器会自动做同样的事情。

根据user667073的建议,除了先重新排序反斜杠替换,并修复引号替换

escape = function (str) {
  return str
    .replace(/[\\]/g, '\\\\')
    .replace(/[\"]/g, '\\\"')
    .replace(/[\/]/g, '\\/')
    .replace(/[\b]/g, '\\b')
    .replace(/[\f]/g, '\\f')
    .replace(/[\n]/g, '\\n')
    .replace(/[\r]/g, '\\r')
    .replace(/[\t]/g, '\\t');
};