一、举例:
比如 :test = {"a": {"b": 1}, "c":3} 取 键值 1
通过形如 “.a.b”形式获取 1。
二、具体代码实现如下:
# _*_ coding: utf-8 _*_
"""
Time: 2024/1/18 21:50
Author:
Version: V 0.1
"""
import collections,json
class JsonToObj(object):
def __init__(self, mapp):
self.__dict_d = dict(mapp)
def __getattr__(self, item):
if hasattr(self.__dict_d, item):
return getattr(self.__dict_d, item)
else:
return JsonToObj.build(self.__dict_d[item])
@classmethod
def build(cls, obj):
if isinstance(obj, collections.Mapping):
return cls(obj)
elif isinstance(obj, collections.MutableSequence):
return [cls.build(item) for item in obj]
else:
return obj
@classmethod
def dict_json(cls, dict_info, output_json):
with open(output_json, 'w') as fw:
fw.writelines(json.dumps(dict_info))
if __name__ == "__main__":
test = {"a": {"b": 1}, "c":3}
ts = JsonToObj(test)
print(ts.a.b)
三、结果输出
如下:输出结果1