如何使用JavaScript避免包含换行字符的JSON字符串?

时间:2022-11-20 22:27:50

I have to form a JSON string in which a value is having new line character. This has to be escaped and then posted using AJAX call. Can any one suggest a way to escape the string with JavaScript. I am not using jQuery.

我必须形成一个JSON字符串,其中一个值具有新的行字符。这需要转义,然后使用AJAX调用发布。任何人都可以建议一种用JavaScript来摆脱字符串的方法。我没有使用jQuery。

13 个解决方案

#1


115  

Take your JSON and .stringify() it. Then use the .replace() method and replace all occurrences of \n with \\n.

以您的JSON和.stringify()为例。然后使用.replace()方法替换所有发生的\n和\\n。

EDIT:

编辑:

As far as I know of, there are no well-known JS libraries for escaping all special characters in a string. But, you could chain the .replace() method and replace all of the special characters like this:

据我所知,目前还没有著名的JS库来摆脱字符串中的所有特殊字符。但是,您可以将.replace()方法链接起来,并替换所有特殊字符:

var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.replace(/\\n/g, "\\n")
                                      .replace(/\\'/g, "\\'")
                                      .replace(/\\"/g, '\\"')
                                      .replace(/\\&/g, "\\&")
                                      .replace(/\\r/g, "\\r")
                                      .replace(/\\t/g, "\\t")
                                      .replace(/\\b/g, "\\b")
                                      .replace(/\\f/g, "\\f");
// myEscapedJSONString is now ready to be POST'ed to the server. 

But that's pretty nasty, isn't it? Enter the beauty of functions, in that they allow you to break code into pieces and keep the main flow of your script clean, and free of 8 chained .replace() calls. So let's put that functionality into a function called, escapeSpecialChars(). Let's go ahead and attach it to the prototype chain of the String object, so we can call escapeSpecialChars() directly on String objects.

但这很糟糕,不是吗?输入功能之美,因为它们允许您将代码分解成块,并保持脚本的主流干净,并释放8个链接的.replace()调用。因此,让我们把这个功能放到一个叫做,escapalchars()的函数中。让我们将它附加到String对象的原型链上,这样我们就可以直接调用String对象上的escapalchars()。

Like so:

像这样:

String.prototype.escapeSpecialChars = function() {
    return this.replace(/\\n/g, "\\n")
               .replace(/\\'/g, "\\'")
               .replace(/\\"/g, '\\"')
               .replace(/\\&/g, "\\&")
               .replace(/\\r/g, "\\r")
               .replace(/\\t/g, "\\t")
               .replace(/\\b/g, "\\b")
               .replace(/\\f/g, "\\f");
};

Once we have defined that function, the main body of our code is as simple as this:

一旦我们定义了这个函数,我们代码的主体就像这样简单:

var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.escapeSpecialChars();
// myEscapedJSONString is now ready to be POST'ed to the server

#2


58  

As per user667073 suggested, except reordering the backslash replacement first, and fixing the quote replacement

按照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');
};

#3


21  

I'm afraid to say that answer given by Alex is rather incorrect, to put it mildly:

我不敢说Alex给出的答案是错误的,委婉地说:

  • Some characters Alex tries to escape are not required to be escaped at all (like & and ');
  • 亚历克斯试图逃避的一些角色根本不需要逃跑(比如&和);
  • \b is not at all the backspace character but rather a word boundary match
  • \b不是在所有的backspace字符,而是一个词边界匹配。
  • Characters required to be escaped are not handled.
  • 需要转义的字符不被处理。

This function

这个函数

escape = function (str) {
    // TODO: escape %x75 4HEXDIG ?? chars
    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')
    ; };

appears to be a better approximation.

似乎是一个更好的近似。

#4


19  

Like you, I have been looking into several comments and post to replace special escape characters in my JSON which contains html object inside that.

和您一样,我一直在查看一些注释和post,以替换JSON中包含html对象的特殊转义字符。

My object is to remove the special characters in JSON object and also render the html which is inside the json object.

我的对象是删除JSON对象中的特殊字符,并呈现在JSON对象中的html。

Here is what I did and hope its very simple to use.

这就是我所做的,并希望它的使用非常简单。

First I did JSON.stringify my json object and JSON.parse the result.

首先,我做了JSON。stringify我的json对象和json。解析结果。

For eg:

如:

JSON.parse(JSON.stringify(jsonObject));

And it solves my problem and done using Pure Javascript.

它解决了我的问题并使用了纯Javascript。

#5


10  

A small update for single quotes

单引号的小更新。

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

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

#6


6  

this is an old post. but it may still be helpful for those using angular.fromJson, and JSON.stringify. escape() is deprecated. use this instead,

这是一个旧帖子。但它可能仍然对那些使用angular.fromJson和JSON.stringify的人有帮助。逃避()弃用。使用这个相反,

var uri_enc = encodeURIComponent(uri); //before you post the contents
var uri_dec = decodeURIComponent(uri_enc); //before you display/use the contents.

ref http://www.w3schools.com/jsref/jsref_decodeuricomponent.asp

ref http://www.w3schools.com/jsref/jsref_decodeuricomponent.asp

#7


5  

There is also second parameter on JSON.stringify. So, more elegant solution would be:

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);

#8


4  

This is an old question but the solution did not work well for me as it did not solve all cases. I finally found an answer that did the job here

这是一个老问题,但是解决方案对我来说并不是很有效,因为它并不能解决所有的问题。我终于找到了一个在这里工作的答案。

I will post my combined solution of both using escape and encode uri component:

我将使用escape和encode uri组件来发布我的组合解决方案:

// implement JSON stringify serialization
JSON.stringify = JSON.stringify || function (obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string") obj = '"'+obj+'"';
        return String(obj);
    }
    else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n]; t = typeof(v);
            if (t == "string") v = '"'+v+'"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        var rawString = (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
       return rawString;
    }
};
function escape (key, val) {
    if (typeof(val)!="string") return val;

    var replaced = encodeURIComponent(val);
    return replaced;
}

JSON.stringifyEscaped = function(obj){
    return JSON.stringify(obj,escape);
}

#9


2  

I got same situation in one of my Ajax calls, where JSON was throwing an error due to the newline in the Textarea field. The solution given here didn't worked for me. So i used Javascript's .escape function and it worked fine. Then to retrieve the value from JSON, I just unescaped using .unescape.

我在一个Ajax调用中遇到了相同的情况,在Textarea字段中,JSON由于newline而抛出了一个错误。这里给出的解决方案对我不起作用。我使用了Javascript的。escape函数,它运行得很好。然后从JSON检索值,我只是使用.unescape。

#10


1  

When using any form of Ajax, detailed documentation for the format of responses received from the CGI server seems to be lacking on the Web. Some entries here point out that newlines in returned text or json data must be escaped to prevent infinite loops (hangs) in JSON conversion (possibly created by throwing an uncaught exception), whether done automatically by jQuery or manually using Javascript system or library JSON parsing calls.

当使用任何形式的Ajax时,从CGI服务器收到的响应格式的详细文档似乎在Web上缺乏。这里的一些条目指出,必须转义返回的文本或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.

在程序员发布这个问题的每一个例子中,都提出了不充分的解决方案(大多数情况下,在发送方替换\n),并且删除了问题。当传递不小心嵌入控制转义序列(如Windows路径名)的字符串值时,会显示它们的不足。一个例子是“C:\克里斯\罗伯茨。php”,包含了控制字符c和^ ^ r,这可能会导致JSON转换字符串的{“文件”:“c:\克里斯\罗伯茨。php”}永远循环。生成这些值的一种方法是故意尝试将PHP警告和错误消息从服务器传递给客户机,这是一个合理的想法。

By definition, Ajax uses HTTP connections behind the scenes. Such connections pass data using GET and POST, both of which require encoding sent data to avoid incorrect syntax, including control characters.

根据定义,Ajax在幕后使用HTTP连接。这种连接通过GET和POST传递数据,这两种方式都需要编码发送数据以避免不正确的语法,包括控制字符。

This gives enough of a hint to construct what seems to be a solution (it needs more testing): to use rawurlencode on the PHP (sending) side to encode the data, and unescape on the Javascript (receiving) side to decode the data. In some cases, you will apply these to entire text strings, in other cases you will apply them only to values inside JSON.

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

If this idea turns out to be correct, simple examples can be constructed to help programmers at all levels solve this problem once and for all.

如果这个想法是正确的,那么可以构造简单的例子来帮助所有级别的程序员一次性解决这个问题。

#11


1  

use json_encode() if your server side scripting lang is php, json_encode() escapes the newline & other unexpected tokens for you (if not php look for similar function for your scripting lan)

使用json_encode()如果您的服务器端脚本语言是php, json_encode()会转义为您的新行和其他意外的令牌(如果不是php,请在脚本lan中查找类似的函数)

then use $.parseJSON() in your javascript, done!

然后在javascript中使用$.parseJSON(),完成!

#12


1  

I used the built in jQuery.serialize() to extract the value from a textarea to urlencode the input. The pro part is that you don't have to search replace every special char on your own and i also keep the newlines and escapes html. For serialize to work it seems the input field needs to have a name attribute though and it also adds same attribute to the escaped string which needs to be replaced away. Might not be what you are looking for but it works for me.

我使用了在jQuery.serialize()中构建的值,从一个textarea提取值到urlencode的输入。支持的部分是,你不需要搜索替换你自己的所有特殊字符,我也保留新行和转义html。对于串行化的工作,似乎输入字段需要有一个name属性,并且它也为需要被替换的脱逃字符串添加了相同的属性。也许不是你想要的,但对我来说很有效。

var myinputfield = jQuery("#myinputfield"); 
var text = myinputfield.serialize();
text = text.replace(myinputfield.attr('name') + '=','');

#13


0  

Looks like this is an ancient post really :-) But guys, the best workaround I have for this, to be 100% that it works without complicated code, is to use both functions of encoding/decoding to base64. These are atob() and btoa(). By far the easiest and best way, no need to worry if you missed any characters to be escaped.

看起来这是一个古老的帖子:-)但是,各位,我所拥有的最好的解决方案是,100%的工作,没有复杂的代码,是使用两个函数的编码/解码到base64。这些是atob()和btoa()。到目前为止,最简单和最好的方法,没有必要担心,如果你错过了任何一个字符被转义。

George

乔治

#1


115  

Take your JSON and .stringify() it. Then use the .replace() method and replace all occurrences of \n with \\n.

以您的JSON和.stringify()为例。然后使用.replace()方法替换所有发生的\n和\\n。

EDIT:

编辑:

As far as I know of, there are no well-known JS libraries for escaping all special characters in a string. But, you could chain the .replace() method and replace all of the special characters like this:

据我所知,目前还没有著名的JS库来摆脱字符串中的所有特殊字符。但是,您可以将.replace()方法链接起来,并替换所有特殊字符:

var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.replace(/\\n/g, "\\n")
                                      .replace(/\\'/g, "\\'")
                                      .replace(/\\"/g, '\\"')
                                      .replace(/\\&/g, "\\&")
                                      .replace(/\\r/g, "\\r")
                                      .replace(/\\t/g, "\\t")
                                      .replace(/\\b/g, "\\b")
                                      .replace(/\\f/g, "\\f");
// myEscapedJSONString is now ready to be POST'ed to the server. 

But that's pretty nasty, isn't it? Enter the beauty of functions, in that they allow you to break code into pieces and keep the main flow of your script clean, and free of 8 chained .replace() calls. So let's put that functionality into a function called, escapeSpecialChars(). Let's go ahead and attach it to the prototype chain of the String object, so we can call escapeSpecialChars() directly on String objects.

但这很糟糕,不是吗?输入功能之美,因为它们允许您将代码分解成块,并保持脚本的主流干净,并释放8个链接的.replace()调用。因此,让我们把这个功能放到一个叫做,escapalchars()的函数中。让我们将它附加到String对象的原型链上,这样我们就可以直接调用String对象上的escapalchars()。

Like so:

像这样:

String.prototype.escapeSpecialChars = function() {
    return this.replace(/\\n/g, "\\n")
               .replace(/\\'/g, "\\'")
               .replace(/\\"/g, '\\"')
               .replace(/\\&/g, "\\&")
               .replace(/\\r/g, "\\r")
               .replace(/\\t/g, "\\t")
               .replace(/\\b/g, "\\b")
               .replace(/\\f/g, "\\f");
};

Once we have defined that function, the main body of our code is as simple as this:

一旦我们定义了这个函数,我们代码的主体就像这样简单:

var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.escapeSpecialChars();
// myEscapedJSONString is now ready to be POST'ed to the server

#2


58  

As per user667073 suggested, except reordering the backslash replacement first, and fixing the quote replacement

按照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');
};

#3


21  

I'm afraid to say that answer given by Alex is rather incorrect, to put it mildly:

我不敢说Alex给出的答案是错误的,委婉地说:

  • Some characters Alex tries to escape are not required to be escaped at all (like & and ');
  • 亚历克斯试图逃避的一些角色根本不需要逃跑(比如&和);
  • \b is not at all the backspace character but rather a word boundary match
  • \b不是在所有的backspace字符,而是一个词边界匹配。
  • Characters required to be escaped are not handled.
  • 需要转义的字符不被处理。

This function

这个函数

escape = function (str) {
    // TODO: escape %x75 4HEXDIG ?? chars
    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')
    ; };

appears to be a better approximation.

似乎是一个更好的近似。

#4


19  

Like you, I have been looking into several comments and post to replace special escape characters in my JSON which contains html object inside that.

和您一样,我一直在查看一些注释和post,以替换JSON中包含html对象的特殊转义字符。

My object is to remove the special characters in JSON object and also render the html which is inside the json object.

我的对象是删除JSON对象中的特殊字符,并呈现在JSON对象中的html。

Here is what I did and hope its very simple to use.

这就是我所做的,并希望它的使用非常简单。

First I did JSON.stringify my json object and JSON.parse the result.

首先,我做了JSON。stringify我的json对象和json。解析结果。

For eg:

如:

JSON.parse(JSON.stringify(jsonObject));

And it solves my problem and done using Pure Javascript.

它解决了我的问题并使用了纯Javascript。

#5


10  

A small update for single quotes

单引号的小更新。

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

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

#6


6  

this is an old post. but it may still be helpful for those using angular.fromJson, and JSON.stringify. escape() is deprecated. use this instead,

这是一个旧帖子。但它可能仍然对那些使用angular.fromJson和JSON.stringify的人有帮助。逃避()弃用。使用这个相反,

var uri_enc = encodeURIComponent(uri); //before you post the contents
var uri_dec = decodeURIComponent(uri_enc); //before you display/use the contents.

ref http://www.w3schools.com/jsref/jsref_decodeuricomponent.asp

ref http://www.w3schools.com/jsref/jsref_decodeuricomponent.asp

#7


5  

There is also second parameter on JSON.stringify. So, more elegant solution would be:

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);

#8


4  

This is an old question but the solution did not work well for me as it did not solve all cases. I finally found an answer that did the job here

这是一个老问题,但是解决方案对我来说并不是很有效,因为它并不能解决所有的问题。我终于找到了一个在这里工作的答案。

I will post my combined solution of both using escape and encode uri component:

我将使用escape和encode uri组件来发布我的组合解决方案:

// implement JSON stringify serialization
JSON.stringify = JSON.stringify || function (obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string") obj = '"'+obj+'"';
        return String(obj);
    }
    else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n]; t = typeof(v);
            if (t == "string") v = '"'+v+'"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        var rawString = (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
       return rawString;
    }
};
function escape (key, val) {
    if (typeof(val)!="string") return val;

    var replaced = encodeURIComponent(val);
    return replaced;
}

JSON.stringifyEscaped = function(obj){
    return JSON.stringify(obj,escape);
}

#9


2  

I got same situation in one of my Ajax calls, where JSON was throwing an error due to the newline in the Textarea field. The solution given here didn't worked for me. So i used Javascript's .escape function and it worked fine. Then to retrieve the value from JSON, I just unescaped using .unescape.

我在一个Ajax调用中遇到了相同的情况,在Textarea字段中,JSON由于newline而抛出了一个错误。这里给出的解决方案对我不起作用。我使用了Javascript的。escape函数,它运行得很好。然后从JSON检索值,我只是使用.unescape。

#10


1  

When using any form of Ajax, detailed documentation for the format of responses received from the CGI server seems to be lacking on the Web. Some entries here point out that newlines in returned text or json data must be escaped to prevent infinite loops (hangs) in JSON conversion (possibly created by throwing an uncaught exception), whether done automatically by jQuery or manually using Javascript system or library JSON parsing calls.

当使用任何形式的Ajax时,从CGI服务器收到的响应格式的详细文档似乎在Web上缺乏。这里的一些条目指出,必须转义返回的文本或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.

在程序员发布这个问题的每一个例子中,都提出了不充分的解决方案(大多数情况下,在发送方替换\n),并且删除了问题。当传递不小心嵌入控制转义序列(如Windows路径名)的字符串值时,会显示它们的不足。一个例子是“C:\克里斯\罗伯茨。php”,包含了控制字符c和^ ^ r,这可能会导致JSON转换字符串的{“文件”:“c:\克里斯\罗伯茨。php”}永远循环。生成这些值的一种方法是故意尝试将PHP警告和错误消息从服务器传递给客户机,这是一个合理的想法。

By definition, Ajax uses HTTP connections behind the scenes. Such connections pass data using GET and POST, both of which require encoding sent data to avoid incorrect syntax, including control characters.

根据定义,Ajax在幕后使用HTTP连接。这种连接通过GET和POST传递数据,这两种方式都需要编码发送数据以避免不正确的语法,包括控制字符。

This gives enough of a hint to construct what seems to be a solution (it needs more testing): to use rawurlencode on the PHP (sending) side to encode the data, and unescape on the Javascript (receiving) side to decode the data. In some cases, you will apply these to entire text strings, in other cases you will apply them only to values inside JSON.

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

If this idea turns out to be correct, simple examples can be constructed to help programmers at all levels solve this problem once and for all.

如果这个想法是正确的,那么可以构造简单的例子来帮助所有级别的程序员一次性解决这个问题。

#11


1  

use json_encode() if your server side scripting lang is php, json_encode() escapes the newline & other unexpected tokens for you (if not php look for similar function for your scripting lan)

使用json_encode()如果您的服务器端脚本语言是php, json_encode()会转义为您的新行和其他意外的令牌(如果不是php,请在脚本lan中查找类似的函数)

then use $.parseJSON() in your javascript, done!

然后在javascript中使用$.parseJSON(),完成!

#12


1  

I used the built in jQuery.serialize() to extract the value from a textarea to urlencode the input. The pro part is that you don't have to search replace every special char on your own and i also keep the newlines and escapes html. For serialize to work it seems the input field needs to have a name attribute though and it also adds same attribute to the escaped string which needs to be replaced away. Might not be what you are looking for but it works for me.

我使用了在jQuery.serialize()中构建的值,从一个textarea提取值到urlencode的输入。支持的部分是,你不需要搜索替换你自己的所有特殊字符,我也保留新行和转义html。对于串行化的工作,似乎输入字段需要有一个name属性,并且它也为需要被替换的脱逃字符串添加了相同的属性。也许不是你想要的,但对我来说很有效。

var myinputfield = jQuery("#myinputfield"); 
var text = myinputfield.serialize();
text = text.replace(myinputfield.attr('name') + '=','');

#13


0  

Looks like this is an ancient post really :-) But guys, the best workaround I have for this, to be 100% that it works without complicated code, is to use both functions of encoding/decoding to base64. These are atob() and btoa(). By far the easiest and best way, no need to worry if you missed any characters to be escaped.

看起来这是一个古老的帖子:-)但是,各位,我所拥有的最好的解决方案是,100%的工作,没有复杂的代码,是使用两个函数的编码/解码到base64。这些是atob()和btoa()。到目前为止,最简单和最好的方法,没有必要担心,如果你错过了任何一个字符被转义。

George

乔治