Skip to content

Instantly share code, notes, and snippets.

@alixedi
Last active September 16, 2015 11:19
Show Gist options
  • Save alixedi/87334264e9b4a2dff3e9 to your computer and use it in GitHub Desktop.
Save alixedi/87334264e9b4a2dff3e9 to your computer and use it in GitHub Desktop.
Neat trick to deal with bunch of JSON records.
import json
class Record(object):
"""
A simple trick that allows you to do `record.name`, 'record.age'
instead of `record['name']`, `record['age']`.
>>> import json
>>> data = json.dumps([{'name': 'jack', 'user': {'id': 21}}])
>>> recs = Record.make_records(data)
>>> recs[0].name
u'jack'
>>> recs[0].user.id
21
"""
def __init__(self, rec):
for fld in rec:
if isinstance(rec[fld], dict):
rec[fld] = Record(rec[fld])
self.__dict__.update(**rec)
@classmethod
def make_records(cls, data):
return map(lambda rec: Record(rec), json.loads(data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment