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
Add a ment  | 

3 Answers 3

Reset to default 4

Building 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