Created
February 16, 2017 15:46
-
-
Save gbinside/9a7154c1de05608811da8da3bf335bfd to your computer and use it in GitHub Desktop.
Load a JSON into numed tuples.
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 | |
from collections import namedtuple | |
from decimal import Decimal | |
def rename(v, key): | |
try: | |
if v.__class__.__name__ == 'Main': | |
name = key.replace('_', ' ').capitalize().replace(' ', '') | |
NewClass = namedtuple(name, v._fields) | |
return NewClass(**(v._asdict())) | |
except AttributeError: | |
pass | |
return v | |
def fx(l): | |
keys = [x[0] for x in l] | |
LocalClass = namedtuple('Main', keys) | |
vals = [rename(x[1], keys[i]) for i, x in enumerate(l)] | |
return LocalClass(*vals) | |
s = '{"a":"data","b":"datab", "c":{"a":1.2}, "error":{"di":"data"}}' | |
ret = json.loads(s, object_pairs_hook=fx, parse_float=Decimal) | |
print ret | |
# output | |
# Main(a=u'data', b=u'datab', c=C(a=Decimal('1.2')), error=Error(di=u'data')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment