Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify and unicode characters

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.

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.

Ok, I forgot: I can't modify the string after JSON.stringify, it's part of the framework without workaround and we don't want to fork the whole package.

like image 970
indriq Avatar asked Jul 27 '15 09:07

indriq


2 Answers

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));
like image 154
georg Avatar answered Nov 20 '22 12:11

georg


This should get you to where you want. I heavily based this on this question: 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.

like image 1
Danny Sullivan Avatar answered Nov 20 '22 12:11

Danny Sullivan