[issue5381] json need object_pairs_hook

Raymond Hettinger report at bugs.python.org
Fri Feb 27 09:37:56 CET 2009


New submission from Raymond Hettinger <rhettinger at users.sourceforge.net>:

If PEP372 goes through, Python is going to gain an ordered dict soon.

The json module's encoder works well with it:

>>> items = [('one', 1), ('two', 2), ('three',3), ('four',4), ('five',5)]
>>> json.dumps(OrderedDict(items))
'{"one": 1, "two": 2, "three": 3, "four": 4, "five": 5}'

But the decoder doesn't fare so well.  The existing object_hook for the
decoder passes in a dictionary instead of a list of pairs.  So, all the
ordering information is lost:

>>> jtext = '{"one": 1, "two": 2, "three": 3, "four": 4, "five": 5}'
>>> json.loads(jtext, object_hook=OrderedDict)
OrderedDict({u'four': 4, u'three': 3, u'five': 5, u'two': 2, u'one': 1})

A solution is to provide an alternate hook that emits a sequence of
pairs.  If present, that hook should run instead of object_hook.  A
rough proof-of-concept patch is attached.

FWIW, sample ordered dict code is at: 
  http://code.activestate.com/recipes/576669/

----------
assignee: bob.ippolito
components: Library (Lib)
files: json_hook.diff
keywords: patch
messages: 82825
nosy: bob.ippolito, rhettinger
priority: normal
severity: normal
status: open
title: json need object_pairs_hook
type: feature request
versions: Python 2.7, Python 3.1
Added file: http://bugs.python.org/file13201/json_hook.diff

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue5381>
_______________________________________


More information about the Python-bugs-list mailing list