admin管理员组文章数量:1402826
I have an ajax request with dataType: 'json'
The json received (being well formed) contains strings with newlines escaped
i.e '{ "a" : "x\\r\\nx" }'
unfortunately the resultant data object in the ajax done function now also contains the newline in that form ("\\r\\n")
I want all string fields in the ajax result data object to be unescaped so that in this case I will get
data = { a:"xNEWLINEx" }
Is there a general way to do this ? assume data may have nested arrays and dictionaries each containing strings which can have newlines (or other escaped special characters)
I have an ajax request with dataType: 'json'
The json received (being well formed) contains strings with newlines escaped
i.e '{ "a" : "x\\r\\nx" }'
unfortunately the resultant data object in the ajax done function now also contains the newline in that form ("\\r\\n")
I want all string fields in the ajax result data object to be unescaped so that in this case I will get
data = { a:"xNEWLINEx" }
Is there a general way to do this ? assume data may have nested arrays and dictionaries each containing strings which can have newlines (or other escaped special characters)
Share Improve this question edited May 22, 2015 at 4:57 kofifus asked May 21, 2015 at 6:41 kofifuskofifus 19.4k23 gold badges118 silver badges185 bronze badges 1-
Why doesn’t the client just send
{"a":"x\r\nx"}
instead? – binki Commented Apr 2, 2017 at 17:42
3 Answers
Reset to default 4Building on the response from yangguang, here is a plete solution:
// 'unescape' all special characters in all strings in an object that was created from JSON (ie, ajax reply)
function jUnescape(obj) {
var j = JSON.stringify(obj);
['b', 'f', 'n', 'r', 't', 'u'].forEach(function(c) {
j=j.split('\\\\' + c).join('\\' + c);
});
j = j.split('\\\\\\"').join('\\"');
j = j.split('\\\\\\\\').join('\\\\');
return JSON.parse(j);
}
see jsfiddle
You can use replace
:
data.a = data.a.replace('\\', '\');
You can also use unescape
(Warning: Deprecated):
data.a = unescape(data.a);
Docs: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/unescape
For Objects:
for (var key in data) {
data[key] = unescape(data[key]);
}
you can try:
var data = { a: "x\\r\\nx" };
data = JSON.parse(JSON.stringify(data));
console.log('data', data);
//Object {a: "x\r\nx"}
for more "\", you can try:
var data = { a: "x\\\\r\\\\nx" };
data = JSON.stringify(data);
data = data.replace(/\\+r\\+n/g,'\\\\r\\\\n');
data = JSON.parse(data);
console.log('data', data);
//Object {a: "x\r\nx"}
本文标签: javascriptunescape special characters in ajax response dataStack Overflow
版权声明:本文标题:javascript - unescape special characters in ajax response data - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744373317a2603137.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论