views:

333

answers:

2

I am using json with unicode text, and having a problem with the IE8 native json implementation.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
<script>
    var stringified = JSON.stringify("สวัสดี olé");
    alert(stringified);
</script>

Using json2.js or FireFox native json, the alert() string is the same as in the original one. IE8 on the other hand returns Unicode values rather than the original text \u0e2a\u0e27\u0e31\u0e2a\u0e14\u0e35 ol\u00e9 . Is there an easy way to make IE behave like the others, or convert this string to how it should be ? And would you regard this as a bug in IE, I thought native json implementations were supposed to be drop-in identical replacements for json2.js ?

Edit: An repro on jsfiddle using the above code - http://jsfiddle.net/vV4uz/

+1  A: 

If this is before sending to the server, you can encode it first encodeURIComponent(JSON.stringify("สวัสดี olé")) and use a utf8 decoder on the server

mplungjan
Thanks. I don't mind doing the decoding on the server if need be, although it's not ideal as it'd mean the server getting different values depending on which browser was being used. How would I then "utf 8 decode it on the server" though (in C#) , I'm still a bit lost...? I already use encodeURIComponent when sending to the server, but that doesn't really change the problem.
miket2e
http://briancaos.wordpress.com/2009/03/31/decodeuricomponent-equivalent-in-c/I do not see why you would get different data depending on browser, IE and FF both support encodeURIComponent
mplungjan
The data passed in is different depending on browser (as in the original question), so the output is different too. encodeURIComponent just lets me shift the problem from client to server, but I'm still looking for a way to actually correct the problem with either Javascript on the client or C# on the server.
miket2e
A: 

To answer my own question - Apparently this is not natively possible in IE8, but it does work correctly in the IE9 Beta.

A fix is possible though:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
<script>
    var stringified = JSON.stringify("สวัสดี olé");
    stringified  = unescape(stringified.replace(/\\u/g, '%u'));
    alert(stringified);
</script>

Which will correctly alert() back the original string on all of IE, FF and Chrome.

miket2e