javascript JSON.stringify 和 unicode 字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31649362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:08:24  来源:igfitidea点击:

JSON.stringify and unicode characters

javascriptjson

提问by indriq

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.stringifyit always gets üregardless of what I've done with it.

我必须将ü之类的字符作为 unicode 字符但作为字符串发送到服务器。所以它必须是\u00fc(6 个字符)而不是字符本身。但不管我用它做了什么,JSON.stringify它总是得到ü之后。

If I use 2 backslashes like \\u00fcthen I get 2 in the JSONstring as well and that's not good either.

如果我使用 2 个反斜杠,\\u00fc那么我JSON也会在字符串中得到 2 个,这也不好。

Any trick to avoid this? It's very annoying.

有什么技巧可以避免这种情况吗?这很烦人。

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.strinfigy 之后修改字符串,它是框架的一部分,没有解决方法,我们不想分叉整个包。

回答by georg

If, for some reason, you want your JSON to be ASCII-safe, replace non-ascii characters after json encoding:

如果出于某种原因,您希望 JSON 是 ASCII 安全的,请在 json 编码后替换非 ascii 字符:

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

回答by Danny Sullivan

This should get you to where you want. I heavily based this on this question: Javascript, convert unicode string to Javascript escape?

这应该能让你到达你想要的地方。我在很大程度上基于这个问题:Javascript, convert unicode string to Javascript escape?

var obj = {"key":"ü"};
var str1 = JSON.stringify(obj);
var str2 = "";
var chr = "";
for(var i = 0; i < str1.length; i++){
    if (str1[i].match(/[^\x00-\x7F]/)){
        chr = "\u" + ("000" + str1[i].charCodeAt(0).toString(16)).substr(-4);
    }else{
        chr = str1[i];
    }
    str2 = str2 + chr;
}  
console.log(str2)

I would recommend though that you look into @t.niese comment about parsing this server side.

我建议您查看有关解析此服务器端的@t.niese 评论。