Created
November 29, 2011 09:21
-
-
Save telendt/1404138 to your computer and use it in GitHub Desktop.
JSONH.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import operator | |
import json | |
class JSONHEncoder(json.JSONEncoder): | |
def iterencode(self, o, *args, **kwargs): | |
if type(o) in (list, tuple) and len(o) and type(o[0]) is dict: | |
d = o[0] | |
keys = d.keys() | |
values = operator.itemgetter(*keys) | |
o = sum(map(values, o), (len(d),) + tuple(keys)) | |
return super(JSONHEncoder, self).iterencode(o, *args, **kwargs) | |
class JSONHDecoder(json.JSONDecoder): | |
def decode(self, s): | |
o = super(JSONHDecoder, self).decode(s) | |
if type(o) is list and len(o) > 1: | |
dict_len = o[0] | |
meta_len = 1 + dict_len | |
assert (len(o) - meta_len) % dict_len == 0 | |
if dict_len > 1: | |
keys = o[1:meta_len] | |
o = [dict(zip(keys, o[i:i+dict_len])) for i in | |
xrange(meta_len, len(o), dict_len)] | |
return o | |
def raw_decode(self, s): | |
raise NotImplementedError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment