parsing json using simplejson

Mike Kazantsev mk.fraggod at gmail.com
Tue Jun 16 00:31:09 EDT 2009


On Mon, 15 Jun 2009 20:01:58 -0700 (PDT)
deostroll <deostroll at 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
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 205 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20090616/91b81a52/attachment.sig>


More information about the Python-list mailing list