Last active
September 16, 2015 11:19
-
-
Save alixedi/87334264e9b4a2dff3e9 to your computer and use it in GitHub Desktop.
Neat trick to deal with bunch of JSON records.
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 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