Packing a simple dictionary into a string - extending struct?
John Machin
sjmachin at lexicon.net
Fri Jun 22 08:59:36 EDT 2007
On Jun 22, 5:08 pm, Jonathan Fine <j... at pytex.org> wrote:
> Jonathan Fine wrote:
> > Thank you for this suggestion. The growing adoption of JSON in Ajax
> > programming is a strong argument for my using it in my application, although
> > I think I'd prefer something a little more binary.
>
> > So it looks like I'll be using JSON.
>
> Well, I tried. But I came across two problems (see below).
>
> First, there's bloat. For binary byte data, one average one
> character becomes just over 4.
>
> Second, there's the inconvenience. I can't simple take a
> sequence of bytes and encode them using JSON. I have to
> turn them into Unicode first. And I guess there's a similar
> problem at the other end.
>
> So I'm going with me own solution:http://mathtran.cvs.sourceforge.net/mathtran/py/bytedict.py?revision=...
>
def unpack(bytes, unpack_entry=unpack_entry):
'''Return dictionary gotten by unpacking supplied bytes.
Both keys and values in the returned dictionary are byte-strings.
'''
bytedict = {}
ptr = 0
while 1:
key, val, ptr = unpack_entry(bytes, ptr)
bytedict[key] = val
if ptr == len(bytes):
break
# That's beautiful code -- as pretty as a cane-toad.
# Well-behaved too, a very elegant response to unpack(pack({}))
# Try this:
blen = len(bytes)
while ptr < blen:
key, val, ptr = unpack_entry(bytes, ptr)
bytedict[key] = val
return bytedict
HTH,
John
More information about the Python-list
mailing list