unescape special characters in ajax response data
ajax, javascript, jquery, json
Solution
Building on the response from yangguang, here is a complete 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
Problem
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)