python字符串转对象工具类,支持对象转字符串,支持多层对象转换。
json_kit.py
import json
"""
json转换工具类
"""
class DictToClass(object):
"""
将字典对象转为class对象
"""
def __init__(self, _obj):
if _obj:
self.__dict__.update(_obj)
class json_kit():
@staticmethod
def str_to_obj(str):
"""
字符串传对象
"""
#字符串转为字典对象
loads = json.loads(str)
#字典对象转为Class对象
obj = DictToClass(loads)
json_kit.attr_dict_to_obj(obj)
return obj
@staticmethod
def attr_dict_to_obj(obj):
"""
将对象属性中的字典对象转为class对象
"""
if obj is None:
return
# 遍历属性的字典对象转为Class对象
attr_list = dir(obj)
for attr in attr_list:
val = getattr(obj, attr)
# print("attr: ",attr," val: ",val," type: ",type(val))
if attr.startswith("__"):
# 跳过私有属性
continue
if type(val) == dict:
# print("dict===>attr: ", attr, " val: ", val, " type: ", type(val))
classVal = DictToClass(val)
setattr(obj, attr, classVal)
#递归处理
json_kit.attr_dict_to_obj(classVal)
@staticmethod
def obj_to_str(obj):
"""
对象转json字符串
"""
str = json.dumps(obj,default=lambda o: o.__dict__,ensure_ascii=False)
return str
if __name__ == '__main__':
obj = json_kit.str_to_obj('{"name":"布布","age":22,"cards":[1,2,3],"child":{"name":"毛巾","age":10,"child":{"name":"鲁伯特娃娃","age":1}}}')
print("字符串传对象",obj)
print(obj.name)
print(obj.child.name)
print(obj.child.child.name)
str = json_kit.obj_to_str(obj)
print("对象转字符串",str)