<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Shugo's Blog comments on to_json hack for Safari</title>
    <link>http://blog.shugo.net/</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>Shugo's Blog comments</description>
    <item>
      <title>"to_json hack for Safari" by shugo</title>
      <description>&lt;p&gt;I found the reason why multibyte characters are encoded in to_json. Safari can't handle UTF-8 strings in text/javascript correctly:(&lt;/p&gt;

&lt;p&gt;Here is new code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class String
  JSON_ESCAPED = {
     "\010" =&amp;gt;  '\b',
     "\f" =&amp;gt;    '\f',
     "\n" =&amp;gt;    '\n',
     "\r" =&amp;gt;    '\r',
     "\t" =&amp;gt;    '\t',
     '"' =&amp;gt;     '\"',
     '\\' =&amp;gt;    '\\\\'
  }

  def to_json
    return '"' + gsub(/[\010\f\n\r\t"\\]/) { |s|
      JSON_ESCAPED[s]
    }.gsub(/([\xC0-\xDF][\x80-\xBF]|
             [\xE0-\xEF][\x80-\xBF]{2}|
             [\xF0-\xF7][\x80-\xBF]{3})+/ux) { |s|
      s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/, '\\\\u\&amp;amp;')
    } + '"'
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I created a patch for ActiveSupport (trac of Rails is down, so I can't attach this patch to the ticket).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://shugo.net/tmp/to_json-2.diff"&gt;to_json-2.diff&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <pubDate>Sat, 15 Jul 2006 17:30:00 JST</pubDate>
      <guid>&lt;a href="/articles/2006/07/15/to_json-hack-for-safari"&gt;to_json hack for Safari&lt;/a&gt;</guid>
      <link>&lt;a href="/articles/2006/07/15/to_json-hack-for-safari"&gt;to_json hack for Safari&lt;/a&gt;</link>
    </item>
  </channel>
</rss>
