Files
abot/utils/json_converter.py
2025-04-22 13:43:03 +08:00

96 lines
2.9 KiB
Python

# -*- coding: utf-8 -*-
"""
JSON数据转换工具
用于将JSON数据转换为Python对象
"""
class DictObject:
"""将字典转换为对象,使得可以通过属性访问"""
def __init__(self, data):
for key, value in data.items():
if isinstance(value, dict):
setattr(self, key, DictObject(value))
elif isinstance(value, list):
setattr(self, key, [
DictObject(item) if isinstance(item, dict) else item
for item in value
])
else:
setattr(self, key, value)
def __repr__(self):
"""打印对象时的表示形式"""
attrs = ', '.join(f"{key}={repr(value)}" for key, value in self.__dict__.items())
return f"{self.__class__.__name__}({attrs})"
def to_dict(self):
"""将对象转换回字典"""
result = {}
for key, value in self.__dict__.items():
if isinstance(value, DictObject):
result[key] = value.to_dict()
elif isinstance(value, list):
result[key] = [
item.to_dict() if isinstance(item, DictObject) else item
for item in value
]
else:
result[key] = value
return result
def json_to_object(json_data):
"""
将JSON数据转换为Python对象
Args:
json_data: JSON字符串或字典
Returns:
DictObject: 转换后的Python对象
"""
import json
# 如果输入是字符串,则解析为字典
if isinstance(json_data, str):
data = json.loads(json_data)
else:
data = json_data
# 转换为对象
return DictObject(data)
# 使用示例
if __name__ == "__main__":
# 示例JSON数据
example_json = {
"ret": 200,
"msg": "操作成功",
"data": {
"wxid": "zhangchuan2288",
"nickName": "朝夕。",
"mobile": "18761670817",
"uin": 1042679712,
"sex": 1,
"province": "Jiangsu",
"city": "Xuzhou",
"signature": ".......",
"country": "CN",
"bigHeadImgUrl": "https://wx.qlogo.cn/mmhead/ver_1/REoLX7KfdibFAgDbtoeXGNjE6sGa8NCib8UaiazlekKjuLneCvicM4xQpuEbZWjjQooSicsKEbKdhqCOCpTHWtnBqdJicJ0I3CgZumwJ6SxR3ibuNs/0",
"smallHeadImgUrl": "https://wx.qlogo.cn/mmhead/ver_1/REoLX7KfdibFAgDbtoeXGNjE6sGa8NCib8UaiazlekKjuLneCvicM4xQpuEbZWjjQooSicsKEbKdhqCOCpTHWtnBqdJicJ0I3CgZumwJ6SxR3ibuNs/132",
"regCountry": "CN",
"snsBgImg": "http://shmmsns.qpic.cn/mmsns/FzeKA69P5uIdqPfQxp59LvOohoE2iaiaj86IBH1jl0F76aGvg8AlU7giaMtBhQ3bPibunbhVLb3aEq4/0"
}
}
# 转换为对象
obj = json_to_object(example_json)
# 通过属性访问
print(f"返回码: {obj.ret}")
print(f"消息: {obj.msg}")
print(f"wxid: {obj.data.wxid}")
# 转换回字典
dict_data = obj.to_dict()
print(f"转换回字典: {dict_data}")