Advertisement
Guest User

Untitled

a guest
Feb 7th, 2014
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.18 KB | None | 0 0
  1. ========================= t.py
  2.  
  3. #!/usr/bin/env python
  4.  
  5. import encoder
  6. import gtk
  7.  
  8. encoder.c_make_encoder = None
  9.  
  10. print encoder.JSONEncoder().encode({
  11. gtk.PAGE_ORIENTATION_PORTRAIT: [
  12. gtk.PAGE_ORIENTATION_LANDSCAPE
  13. ],
  14. gtk.PAGE_ORIENTATION_LANDSCAPE: gtk.PAGE_ORIENTATION_PORTRAIT })
  15.  
  16. ========================= diff for encoder.py
  17.  
  18. $ diff /usr/lib/python2.7/json/encoder.py encoder.py
  19. 281a282,287
  20. > def encodeInt(value):
  21. > try:
  22. > return value.value_name
  23. > except:
  24. > return str(value)
  25. >
  26. 315c321
  27. < yield buf + str(value)
  28. ---
  29. > yield buf + encodeInt(value)
  30. 372c378
  31. < key = str(key)
  32. ---
  33. > key = encodeInt(key)
  34. 392c398
  35. < yield str(value)
  36. ---
  37. > yield encodeInt(value)
  38. 421c427
  39. < yield str(o)
  40. ---
  41. > yield encodeInt(o)
  42.  
  43.  
  44. ========================= patched version of encoder.py
  45.  
  46. """Implementation of JSONEncoder
  47. """
  48. import re
  49.  
  50. try:
  51. from _json import encode_basestring_ascii as c_encode_basestring_ascii
  52. except ImportError:
  53. c_encode_basestring_ascii = None
  54. try:
  55. from _json import make_encoder as c_make_encoder
  56. except ImportError:
  57. c_make_encoder = None
  58.  
  59. ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
  60. ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
  61. HAS_UTF8 = re.compile(r'[\x80-\xff]')
  62. ESCAPE_DCT = {
  63. '\\': '\\\\',
  64. '"': '\\"',
  65. '\b': '\\b',
  66. '\f': '\\f',
  67. '\n': '\\n',
  68. '\r': '\\r',
  69. '\t': '\\t',
  70. }
  71. for i in range(0x20):
  72. ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i))
  73. #ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
  74.  
  75. # Assume this produces an infinity on all machines (probably not guaranteed)
  76. INFINITY = float('1e66666')
  77. FLOAT_REPR = repr
  78.  
  79. def encode_basestring(s):
  80. """Return a JSON representation of a Python string
  81.  
  82. """
  83. def replace(match):
  84. return ESCAPE_DCT[match.group(0)]
  85. return '"' + ESCAPE.sub(replace, s) + '"'
  86.  
  87.  
  88. def py_encode_basestring_ascii(s):
  89. """Return an ASCII-only JSON representation of a Python string
  90.  
  91. """
  92. if isinstance(s, str) and HAS_UTF8.search(s) is not None:
  93. s = s.decode('utf-8')
  94. def replace(match):
  95. s = match.group(0)
  96. try:
  97. return ESCAPE_DCT[s]
  98. except KeyError:
  99. n = ord(s)
  100. if n < 0x10000:
  101. return '\\u{0:04x}'.format(n)
  102. #return '\\u%04x' % (n,)
  103. else:
  104. # surrogate pair
  105. n -= 0x10000
  106. s1 = 0xd800 | ((n >> 10) & 0x3ff)
  107. s2 = 0xdc00 | (n & 0x3ff)
  108. return '\\u{0:04x}\\u{1:04x}'.format(s1, s2)
  109. #return '\\u%04x\\u%04x' % (s1, s2)
  110. return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
  111.  
  112.  
  113. encode_basestring_ascii = (
  114. c_encode_basestring_ascii or py_encode_basestring_ascii)
  115.  
  116. class JSONEncoder(object):
  117. """Extensible JSON <http://json.org> encoder for Python data structures.
  118.  
  119. Supports the following objects and types by default:
  120.  
  121. +-------------------+---------------+
  122. | Python | JSON |
  123. +===================+===============+
  124. | dict | object |
  125. +-------------------+---------------+
  126. | list, tuple | array |
  127. +-------------------+---------------+
  128. | str, unicode | string |
  129. +-------------------+---------------+
  130. | int, long, float | number |
  131. +-------------------+---------------+
  132. | True | true |
  133. +-------------------+---------------+
  134. | False | false |
  135. +-------------------+---------------+
  136. | None | null |
  137. +-------------------+---------------+
  138.  
  139. To extend this to recognize other objects, subclass and implement a
  140. ``.default()`` method with another method that returns a serializable
  141. object for ``o`` if possible, otherwise it should call the superclass
  142. implementation (to raise ``TypeError``).
  143.  
  144. """
  145. item_separator = ', '
  146. key_separator = ': '
  147. def __init__(self, skipkeys=False, ensure_ascii=True,
  148. check_circular=True, allow_nan=True, sort_keys=False,
  149. indent=None, separators=None, encoding='utf-8', default=None):
  150. """Constructor for JSONEncoder, with sensible defaults.
  151.  
  152. If skipkeys is false, then it is a TypeError to attempt
  153. encoding of keys that are not str, int, long, float or None. If
  154. skipkeys is True, such items are simply skipped.
  155.  
  156. If ensure_ascii is true, the output is guaranteed to be str
  157. objects with all incoming unicode characters escaped. If
  158. ensure_ascii is false, the output will be unicode object.
  159.  
  160. If check_circular is true, then lists, dicts, and custom encoded
  161. objects will be checked for circular references during encoding to
  162. prevent an infinite recursion (which would cause an OverflowError).
  163. Otherwise, no such check takes place.
  164.  
  165. If allow_nan is true, then NaN, Infinity, and -Infinity will be
  166. encoded as such. This behavior is not JSON specification compliant,
  167. but is consistent with most JavaScript based encoders and decoders.
  168. Otherwise, it will be a ValueError to encode such floats.
  169.  
  170. If sort_keys is true, then the output of dictionaries will be
  171. sorted by key; this is useful for regression tests to ensure
  172. that JSON serializations can be compared on a day-to-day basis.
  173.  
  174. If indent is a non-negative integer, then JSON array
  175. elements and object members will be pretty-printed with that
  176. indent level. An indent level of 0 will only insert newlines.
  177. None is the most compact representation.
  178.  
  179. If specified, separators should be a (item_separator, key_separator)
  180. tuple. The default is (', ', ': '). To get the most compact JSON
  181. representation you should specify (',', ':') to eliminate whitespace.
  182.  
  183. If specified, default is a function that gets called for objects
  184. that can't otherwise be serialized. It should return a JSON encodable
  185. version of the object or raise a ``TypeError``.
  186.  
  187. If encoding is not None, then all input strings will be
  188. transformed into unicode using that encoding prior to JSON-encoding.
  189. The default is UTF-8.
  190.  
  191. """
  192.  
  193. self.skipkeys = skipkeys
  194. self.ensure_ascii = ensure_ascii
  195. self.check_circular = check_circular
  196. self.allow_nan = allow_nan
  197. self.sort_keys = sort_keys
  198. self.indent = indent
  199. if separators is not None:
  200. self.item_separator, self.key_separator = separators
  201. if default is not None:
  202. self.default = default
  203. self.encoding = encoding
  204.  
  205. def default(self, o):
  206. """Implement this method in a subclass such that it returns
  207. a serializable object for ``o``, or calls the base implementation
  208. (to raise a ``TypeError``).
  209.  
  210. For example, to support arbitrary iterators, you could
  211. implement default like this::
  212.  
  213. def default(self, o):
  214. try:
  215. iterable = iter(o)
  216. except TypeError:
  217. pass
  218. else:
  219. return list(iterable)
  220. return JSONEncoder.default(self, o)
  221.  
  222. """
  223. raise TypeError(repr(o) + " is not JSON serializable")
  224.  
  225. def encode(self, o):
  226. """Return a JSON string representation of a Python data structure.
  227.  
  228. >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
  229. '{"foo": ["bar", "baz"]}'
  230.  
  231. """
  232. # This is for extremely simple cases and benchmarks.
  233. if isinstance(o, basestring):
  234. if isinstance(o, str):
  235. _encoding = self.encoding
  236. if (_encoding is not None
  237. and not (_encoding == 'utf-8')):
  238. o = o.decode(_encoding)
  239. if self.ensure_ascii:
  240. return encode_basestring_ascii(o)
  241. else:
  242. return encode_basestring(o)
  243. # This doesn't pass the iterator directly to ''.join() because the
  244. # exceptions aren't as detailed. The list call should be roughly
  245. # equivalent to the PySequence_Fast that ''.join() would do.
  246. chunks = self.iterencode(o, _one_shot=True)
  247. if not isinstance(chunks, (list, tuple)):
  248. chunks = list(chunks)
  249. return ''.join(chunks)
  250.  
  251. def iterencode(self, o, _one_shot=False):
  252. """Encode the given object and yield each string
  253. representation as available.
  254.  
  255. For example::
  256.  
  257. for chunk in JSONEncoder().iterencode(bigobject):
  258. mysocket.write(chunk)
  259.  
  260. """
  261. if self.check_circular:
  262. markers = {}
  263. else:
  264. markers = None
  265. if self.ensure_ascii:
  266. _encoder = encode_basestring_ascii
  267. else:
  268. _encoder = encode_basestring
  269. if self.encoding != 'utf-8':
  270. def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
  271. if isinstance(o, str):
  272. o = o.decode(_encoding)
  273. return _orig_encoder(o)
  274.  
  275. def floatstr(o, allow_nan=self.allow_nan,
  276. _repr=FLOAT_REPR, _inf=INFINITY, _neginf=-INFINITY):
  277. # Check for specials. Note that this type of test is processor
  278. # and/or platform-specific, so do tests which don't depend on the
  279. # internals.
  280.  
  281. if o != o:
  282. text = 'NaN'
  283. elif o == _inf:
  284. text = 'Infinity'
  285. elif o == _neginf:
  286. text = '-Infinity'
  287. else:
  288. return _repr(o)
  289.  
  290. if not allow_nan:
  291. raise ValueError(
  292. "Out of range float values are not JSON compliant: " +
  293. repr(o))
  294.  
  295. return text
  296.  
  297.  
  298. if (_one_shot and c_make_encoder is not None
  299. and self.indent is None and not self.sort_keys):
  300. _iterencode = c_make_encoder(
  301. markers, self.default, _encoder, self.indent,
  302. self.key_separator, self.item_separator, self.sort_keys,
  303. self.skipkeys, self.allow_nan)
  304. else:
  305. _iterencode = _make_iterencode(
  306. markers, self.default, _encoder, self.indent, floatstr,
  307. self.key_separator, self.item_separator, self.sort_keys,
  308. self.skipkeys, _one_shot)
  309. return _iterencode(o, 0)
  310.  
  311. def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
  312. _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
  313. ## HACK: hand-optimized bytecode; turn globals into locals
  314. ValueError=ValueError,
  315. basestring=basestring,
  316. dict=dict,
  317. float=float,
  318. id=id,
  319. int=int,
  320. isinstance=isinstance,
  321. list=list,
  322. long=long,
  323. str=str,
  324. tuple=tuple,
  325. ):
  326.  
  327. def encodeInt(value):
  328. try:
  329. return value.value_name
  330. except:
  331. return str(value)
  332.  
  333. def _iterencode_list(lst, _current_indent_level):
  334. if not lst:
  335. yield '[]'
  336. return
  337. if markers is not None:
  338. markerid = id(lst)
  339. if markerid in markers:
  340. raise ValueError("Circular reference detected")
  341. markers[markerid] = lst
  342. buf = '['
  343. if _indent is not None:
  344. _current_indent_level += 1
  345. newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
  346. separator = _item_separator + newline_indent
  347. buf += newline_indent
  348. else:
  349. newline_indent = None
  350. separator = _item_separator
  351. first = True
  352. for value in lst:
  353. if first:
  354. first = False
  355. else:
  356. buf = separator
  357. if isinstance(value, basestring):
  358. yield buf + _encoder(value)
  359. elif value is None:
  360. yield buf + 'null'
  361. elif value is True:
  362. yield buf + 'true'
  363. elif value is False:
  364. yield buf + 'false'
  365. elif isinstance(value, (int, long)):
  366. yield buf + encodeInt(value)
  367. elif isinstance(value, float):
  368. yield buf + _floatstr(value)
  369. else:
  370. yield buf
  371. if isinstance(value, (list, tuple)):
  372. chunks = _iterencode_list(value, _current_indent_level)
  373. elif isinstance(value, dict):
  374. chunks = _iterencode_dict(value, _current_indent_level)
  375. else:
  376. chunks = _iterencode(value, _current_indent_level)
  377. for chunk in chunks:
  378. yield chunk
  379. if newline_indent is not None:
  380. _current_indent_level -= 1
  381. yield '\n' + (' ' * (_indent * _current_indent_level))
  382. yield ']'
  383. if markers is not None:
  384. del markers[markerid]
  385.  
  386. def _iterencode_dict(dct, _current_indent_level):
  387. if not dct:
  388. yield '{}'
  389. return
  390. if markers is not None:
  391. markerid = id(dct)
  392. if markerid in markers:
  393. raise ValueError("Circular reference detected")
  394. markers[markerid] = dct
  395. yield '{'
  396. if _indent is not None:
  397. _current_indent_level += 1
  398. newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
  399. item_separator = _item_separator + newline_indent
  400. yield newline_indent
  401. else:
  402. newline_indent = None
  403. item_separator = _item_separator
  404. first = True
  405. if _sort_keys:
  406. items = sorted(dct.items(), key=lambda kv: kv[0])
  407. else:
  408. items = dct.iteritems()
  409. for key, value in items:
  410. if isinstance(key, basestring):
  411. pass
  412. # JavaScript is weakly typed for these, so it makes sense to
  413. # also allow them. Many encoders seem to do something like this.
  414. elif isinstance(key, float):
  415. key = _floatstr(key)
  416. elif key is True:
  417. key = 'true'
  418. elif key is False:
  419. key = 'false'
  420. elif key is None:
  421. key = 'null'
  422. elif isinstance(key, (int, long)):
  423. key = encodeInt(key)
  424. elif _skipkeys:
  425. continue
  426. else:
  427. raise TypeError("key " + repr(key) + " is not a string")
  428. if first:
  429. first = False
  430. else:
  431. yield item_separator
  432. yield _encoder(key)
  433. yield _key_separator
  434. if isinstance(value, basestring):
  435. yield _encoder(value)
  436. elif value is None:
  437. yield 'null'
  438. elif value is True:
  439. yield 'true'
  440. elif value is False:
  441. yield 'false'
  442. elif isinstance(value, (int, long)):
  443. yield encodeInt(value)
  444. elif isinstance(value, float):
  445. yield _floatstr(value)
  446. else:
  447. if isinstance(value, (list, tuple)):
  448. chunks = _iterencode_list(value, _current_indent_level)
  449. elif isinstance(value, dict):
  450. chunks = _iterencode_dict(value, _current_indent_level)
  451. else:
  452. chunks = _iterencode(value, _current_indent_level)
  453. for chunk in chunks:
  454. yield chunk
  455. if newline_indent is not None:
  456. _current_indent_level -= 1
  457. yield '\n' + (' ' * (_indent * _current_indent_level))
  458. yield '}'
  459. if markers is not None:
  460. del markers[markerid]
  461.  
  462. def _iterencode(o, _current_indent_level):
  463. if isinstance(o, basestring):
  464. yield _encoder(o)
  465. elif o is None:
  466. yield 'null'
  467. elif o is True:
  468. yield 'true'
  469. elif o is False:
  470. yield 'false'
  471. elif isinstance(o, (int, long)):
  472. yield encodeInt(o)
  473. elif isinstance(o, float):
  474. yield _floatstr(o)
  475. elif isinstance(o, (list, tuple)):
  476. for chunk in _iterencode_list(o, _current_indent_level):
  477. yield chunk
  478. elif isinstance(o, dict):
  479. for chunk in _iterencode_dict(o, _current_indent_level):
  480. yield chunk
  481. else:
  482. if markers is not None:
  483. markerid = id(o)
  484. if markerid in markers:
  485. raise ValueError("Circular reference detected")
  486. markers[markerid] = o
  487. o = _default(o)
  488. for chunk in _iterencode(o, _current_indent_level):
  489. yield chunk
  490. if markers is not None:
  491. del markers[markerid]
  492.  
  493. return _iterencode
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement