On Mon, 15 Jun 2009 20:01:58 -0700 (PDT) deostroll <deostr...@gmail.com> wrote:
> I want to be able to parse it into python objects. Any ideas? JSON objects behave like python dicts (key:val pairs), so why not just use them? Both simplejson and py2.6-json (which is quite similar to the former) do just that, but if you like JS attribute-like key access model you can use it by extending the builtin dict class: import types, collections class AttrDict(dict): '''AttrDict - dict with JS-like key=attr access''' def __init__(self, *argz, **kwz): if len(argz) == 1 and not kwz and isinstance(argz[0], types.StringTypes): super(AttrDict, self).__init__(open(argz[0])) else: super(AttrDict, self).__init__(*argz, **kwz) for k,v in self.iteritems(): setattr(self, k, v) # re-construct all values via factory def __val_factory(self, val): return AttrDict(val) if isinstance(val, collections.Mapping) else val def __getattr__(self, k): return super(AttrDict, self).__getitem__(k) __getitem__ = __getattr__ def __setattr__(self, k, v): return super(AttrDict, self).__setitem__(k, self.__val_factory(v)) __setitem__ = __setattr__ if __name__ == '__main__': import json data = AttrDict(json.loads('{"host": "docs.python.org",' ' "port": 80,' ' "references": [ "collections",' ' "json",' ' "types",' ' "data model" ],' ' "see_also": { "UserDict": "similar, although' ' less flexible dict implementation." } }')) print data.references # You can always use it as a regular dict print 'port' in data print data['see_also'] # Data model propagnates itself to any sub-mappings data.see_also.new_item = dict(x=1, y=2) print data.see_also.keys() data.see_also.new_item['z'] = 3 print data.see_also.new_item.z -- Mike Kazantsev // fraggod.net
signature.asc
Description: PGP signature
-- http://mail.python.org/mailman/listinfo/python-list