diff mercurial/templatefilters.py @ 11890:9dac951d0185 stable

templatefilters: use \uxxxx style escape for JSON string It's embeddable in plain javascript, and also conforms to JSON standard.
author Yuya Nishihara <yuya@tcha.org>
date Wed, 11 Aug 2010 01:06:21 +0900
parents aff419e260f9
children 0bedf3a2062a
line wrap: on
line diff
--- a/mercurial/templatefilters.py	Fri Aug 13 17:21:06 2010 +0200
+++ b/mercurial/templatefilters.py	Wed Aug 11 01:06:21 2010 +0900
@@ -148,7 +148,13 @@
 def jsonescape(s):
     for k, v in _escapes:
         s = s.replace(k, v)
-    return s
+
+    def uescape(c):
+        if ord(c) < 0x80:
+            return c
+        else:
+            return '\\u%04x' % ord(c)
+    return ''.join(uescape(c) for c in s)
 
 def json(obj):
     if obj is None or obj is False or obj is True:
@@ -157,9 +163,9 @@
         return str(obj)
     elif isinstance(obj, str):
         u = unicode(obj, encoding.encoding, 'replace')
-        return '"%s"' % jsonescape(u).encode('utf-8')
+        return '"%s"' % jsonescape(u)
     elif isinstance(obj, unicode):
-        return '"%s"' % jsonescape(obj).encode('utf-8')
+        return '"%s"' % jsonescape(obj)
     elif hasattr(obj, 'keys'):
         out = []
         for k, v in obj.iteritems():