Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correct character encoding in IE8 native json?

I am using json with unicode text, and am 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/

like image 757
Michael Low Avatar asked Apr 03 '10 09:04

Michael Low


People also ask

Is JSON Ascii or UTF-8?

JSON text SHALL be encoded in Unicode. The default encoding is UTF-8.

Can JSON have UTF-8?

The default encoding is UTF-8. (in §6) JSON may be represented using UTF-8, UTF-16, or UTF-32. When JSON is written in UTF-8, JSON is 8bit compatible. When JSON is written in UTF-16 or UTF-32, the binary content-transfer-encoding must be used.

How should JSON be encoded?

JSON text exchanged between systems that are not part of a closed ecosystem MUST be encoded using UTF-8 [RFC3629]. Previous specifications of JSON have not required the use of UTF-8 when transmitting JSON text.

Does JSON use Ascii or Unicode?

JSON data always uses the Unicode character set.


1 Answers

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.

like image 94
Michael Low Avatar answered Sep 27 '22 23:09

Michael Low