unescape ajax响应数据中的特殊字符 [英] unescape special characters in ajax response data

查看:172
本文介绍了unescape ajax响应数据中的特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有dataType的ajax请求:'json'

I have an ajax request with dataType: 'json'

收到的json(格式正确)包含转义换行符的字符串

The json received (being well formed) contains strings with newlines escaped

即'{a:x \\\\\\ nxx}'

遗憾的是,ajax done函数中的结果数据对象现在还包含该格式的换行符(\\\\\\ n)

unfortunately the resultant data object in the ajax done function now also contains the newline in that form ("\\r\\n")

我希望ajax结果数据对象中的所有字符串字段都不转义,这样在这种情况下我会得到

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)

推荐答案

建立在来自yangguang的回复,这是一个完整的解决方案:

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

参见 jsfiddle

这篇关于unescape ajax响应数据中的特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆