Return an ASCII-only JSON representation of a Python string
(s)
| 45 | |
| 46 | |
| 47 | def py_encode_basestring_ascii(s): |
| 48 | """Return an ASCII-only JSON representation of a Python string |
| 49 | |
| 50 | """ |
| 51 | if isinstance(s, str) and HAS_UTF8.search(s) is not None: |
| 52 | s = s.decode('utf-8') |
| 53 | def replace(match): |
| 54 | s = match.group(0) |
| 55 | try: |
| 56 | return ESCAPE_DCT[s] |
| 57 | except KeyError: |
| 58 | n = ord(s) |
| 59 | if n < 0x10000: |
| 60 | #return '\\u{0:04x}'.format(n) |
| 61 | return '\\u%04x' % (n,) |
| 62 | else: |
| 63 | # surrogate pair |
| 64 | n -= 0x10000 |
| 65 | s1 = 0xd800 | ((n >> 10) & 0x3ff) |
| 66 | s2 = 0xdc00 | (n & 0x3ff) |
| 67 | #return '\\u{0:04x}\\u{1:04x}'.format(s1, s2) |
| 68 | return '\\u%04x\\u%04x' % (s1, s2) |
| 69 | return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"' |
| 70 | |
| 71 | |
| 72 | encode_basestring_ascii = ( |