In python, you can easily parse JSON files with the standard json module, but it's a bit dict, so let's make it dot accessible.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
class Json(object):
def __init__(self, **kwargs):
[setattr(self,k,v) for k,v in kwargs.items()]
def hook(dct):
return Json(**dct)
def load(filename):
with open(filename) as f:
obj = json.load(f, object_hook=hook)
return obj
if __name__ == '__main__':
config = load('config.json')
print(config.conf_1) # conf_1
print(config.conf_2.conf_21[0]) # conf_221
config.json
{
"conf_1" : "conf_1",
"conf_2" : {
"conf_21" : "conf_21",
"conf_22" : [ "conf_221", "conf_222" ]
}
}
--Pass ʻobject_hook to the
json.loadmethod. --In
hook specified in ʻobject_hook
, the keyword is expanded and distributed to the constructor of the prepared Json
class.
--In the Json
class, each argument received by the keyword is added as an attribute.
Recommended Posts