JSON.stringify和unicode字符 [英] JSON.stringify and unicode characters
问题描述
我必须将ü等字符作为unicode字符发送到服务器,但作为字符串。所以它必须是 \ u00fc
(6个字符)而不是字符本身。但是在 JSON.stringify
之后,无论我用它做什么,它总是得到ü。
I have to send characters like ü to the server as unicode character but as a string. So it must be \u00fc
(6 characters) not the character itself. But after JSON.stringify
it always gets ü regardless of what I've done with it.
如果我使用2个反斜杠,如 \\\\0000cc
那么我在 JSON
字符串中得到2好吧,这也不好。
If I use 2 backslashes like \\u00fc
then I get 2 in the JSON
string as well and that's not good either.
任何避免这种情况的技巧?这很烦人。
Any trick to avoid this? It's very annoying.
好的,我忘了:我无法在JSON.strinfigy之后修改字符串,它是框架的一部分,没有解决方法,我们不想fork整个包。
Ok, I forgot: I can't modify the string after JSON.strinfigy, it's part of the framework without workaround and we don't want to fork the whole package.
推荐答案
如果由于某种原因,您希望JSON是ASCII安全的,请替换非ascii json编码后的字符:
If, for some reason, you want your JSON to be ASCII-safe, replace non-ascii characters after json encoding:
var obj = {"key":"füßchen", "some": [1,2,3]}
var json = JSON.stringify(obj)
json = json.replace(/[\u007F-\uFFFF]/g, function(chr) {
return "\\u" + ("0000" + chr.charCodeAt(0).toString(16)).substr(-4)
})
document.write(json);
document.write("<br>");
document.write(JSON.parse(json));
这篇关于JSON.stringify和unicode字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!