SDK 兼容 JSON
最近在集成融云 SDK,于是看了下融云的 SDK 源码,发现源码中有一段针对 JSON 的适配,因为针对 IE9 以下不反对 JSON 对象的解决形式,在此分享下
1、长处: 除中文外的字符都会转为 Unicode。
2、毛病:JSON.parse() 应用 eval 进行转换的,这个办法不是很平安,还看到人介绍用 new Function,然而没有测试,这里临时标记下,有空测试下。
if (!window["JSON"]) {window["JSON"] = (function () {function JSON() { }
JSON.parse = function (sJSON) {return eval('(' + sJSON + ')');
};
JSON.stringify = function (value) {return this.str("", {"": value});
};
JSON.str = function (key, holder) {var i, k, v, length, mind = "", partial, value = holder[key], me = this;
if (value && typeof value === "object" && typeof value.toJSON === "function") {value = value.toJSON(key);
}
switch (typeof value) {
case "string":
return me.quote(value);
case "number":
return isFinite(value) ? String(value) : "null";
case "boolean":
case "null":
return String(value);
case "object":
if (!value) {return "null";}
partial = [];
if (Object.prototype.toString.apply(value) === "[object Array]") {
length = value.length;
for (i = 0; i < length; i += 1) {partial[i] = me.str(i, value) || "null";
}
v = partial.length === 0 ? "[]" : "[" + partial.join(",") + "]";
return v;
}
for (k in value) {if (Object.prototype.hasOwnProperty.call(value, k)) {v = me.str(k, value);
if (v) {partial.push(me.quote(k) + ":" + v);
}
}
}
v = partial.length === 0 ? "{}" : "{" + partial.join(",") + "}";
return v;
}
};
JSON.quote = function (string) {
var me = this;
me.rx_escapable.lastIndex = 0;
return me.rx_escapable.test(string) ? '"' + string.replace(me.rx_escapable, function (a) {var c = me.meta[a];
return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"':'"' + string + '"';
};
JSON.rx_escapable = new RegExp('[\\\"\\\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]', "g");
JSON.meta = {
"\b": "\\b",
"":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"': '\\"',
"''":"\\''","\\":"\\\\"
};
return JSON;
})();}
看到这段代码,感觉融云 SDK 在兼容性上还是有解决的,又在 IE7 下做了测试,果然能够稳固运行(这年头还有 IE7,是不是很神奇)
融云官网:https://www.rongcloud.cn
融云文档:https://docs.rongcloud.cn/v4