如何使用 JavaScript 转义包含换行符的 JSON 字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4253367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to escape a JSON string containing newline characters using JavaScript?
提问by Srikant
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。
采纳答案by Alex
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()
调用。因此,让我们将该功能放入一个名为, 的函数中escapeSpecialChars()
。让我们继续前进,并将其连接到prototype chain
该的String
对象,所以我们可以调用escapeSpecialChars()
直接对String对象。
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
回答by Ryan
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');
};
回答by Balasubramani M
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.
像您一样,我一直在查看一些评论并发布帖子以替换其中包含 html 对象的 JSON 中的特殊转义字符。
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.parse 结果。
For eg:
例如:
JSON.parse(JSON.stringify(jsonObject));
And it solves my problem and done using Pure Javascript.
它解决了我的问题并使用 Pure Javascript 完成。
回答by whaefelinger
I'm afraid to say that answer given by Alex is rather incorrect, to put it mildly:
我不敢说亚历克斯给出的答案是相当不正确的,委婉地说:
- 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
- Characters required to be escaped are not handled.
- Alex 尝试转义的某些字符根本不需要转义(例如 & 和 ');
- \b 根本不是退格字符而是单词边界匹配
- 不处理需要转义的字符。
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.
似乎是一个更好的近似值。
回答by Akash Dhawale
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);
回答by Sam
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 的人来说,它可能仍然有帮助。不推荐使用escape()。改用这个,
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
参考http://www.w3schools.com/jsref/jsref_decodeuricomponent.asp
回答by Mitzi
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:
我将发布我使用转义和编码 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);
}
回答by Krunoslav Djakovic
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);
回答by avngr
Use json_encode()if your server side scripting lang is PHP,
json_encode()
escapes the newline & other unexpected tokens for you
(if not using PHP look for similar function for your scripting language)
如果您的服务器端脚本语言是 PHP,请使用json_encode(),为您
json_encode()
转义换行符和其他意外标记(如果不使用 PHP,请为您的脚本语言寻找类似的功能)
then use $.parseJSON()
in your JavaScript, done!
然后$.parseJSON()
在你的 JavaScript 中使用,完成!
回答by Janspeed
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') + '=','');