JSON.stringify and Unicode characters

I need to send characters as ü to the server as a Unicode character, but as a string. Therefore, it should be \u00fc(6 characters), not the character itself. But afterwards JSON.stringifyhe always gets ü , no matter what I did with him.

If I use 2 backslashes of type \\u00fc, then I get 2 per line JSON, and that is not good either.

Any trick to avoid this? This is very annoying.

Ok, I forgot: I cannot change the line after JSON.strinfigy, this is part of the framework without a workaround, and we do not want to decode the whole package.

+4
source share
2 answers

- , JSON ASCII-, ascii json-:

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

, . : Javascript, unicode 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)

, @t.niese .

0

Source: https://habr.com/ru/post/1599843/


All Articles