Python解析json格式配置文件示例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cj675816156/article/details/82670769

ConfigParseJson.py

import json


class JSONObject:
    def __init__(self, d):
        self.__dict__ = d

    def __len__(self):
        return len(self.__dict__)

class ConfigParseJson():
    def __init__(self, cfg):
        self.index = 0
        self.cfg = cfg
        with open(self.cfg, 'r') as cfg_fd:
            self.json = json.load(cfg_fd, object_hook=JSONObject)
        self.keys = list(self.json.__dict__)

    def __getitem__(self, key):
        return eval("self.json.%s" % key)

    def __len__(self):
        return len(self.json)

    def getlen(self, key):
        json_item = eval("self.json.%s" % key)
        return json_item[1] - json_item[0] + 1

    def __iter__(self):
        return self

    def __next__(self):
        if self.index < len(self.json):
            self.index += 1
            return self.keys[self.index - 1]
        else:
            self.index = 0
            raise StopIteration

if __name__ == '__main__':
    configs = ConfigParseJson('config.json')
    print(configs['a'])
    print(len(configs))
    print(configs.getlen('a'))
    for i in configs:
        print(i)
    print('----------------------')
    for i in configs:
        print(i)

需要解析的配置文件为:config.json

{
    "a" : [20, 31],
    "b" : [17, 19],
    "c" : [16, 16],
    "d" : [10, 15],
    "e" : [ 4,  9],
    "f" : [ 0,  3]
}

执行结果:

[20, 31]
6
12
a
b
c
d
e
f
----------------------
a
b
c
d
e
f

猜你喜欢

转载自blog.csdn.net/cj675816156/article/details/82670769