使用json.loads转SimpleNamespace后,如何访问'from'字段内容?
问题描述
现有一段Python代码运行正常:
import json from types import SimpleNamespace data=json.dumps( { "update_id": 992108054, "message": { "delete_chat_photo": False, "new_chat_members": [], "date": 1669931418, "photo": [], "entities": [], "message_id": 110, "group_chat_created": False, "caption_entities": [], "new_chat_photo": [], "supergroup_chat_created": False, "chat": { "type": "private", "first_name": "test_name", "id": 134839552, "last_name": "test_l_name", "username": "test_username" }, "channel_chat_created": False, "text": "test_text", "from": { "last_name": "test_l_name", "is_bot": False, "username": "test_username", "id": 134839552, "first_name": "test_name", "language_code": "en" } } }) x = json.loads(data, object_hook=lambda d: SimpleNamespace(**d)) print(x.message.text, x.message.chat )
但添加以下代码时触发语法错误:
print(x.message.from)
错误信息如下:
File "<ipython-input-179-dec1b9f9affa>", line 1 print(x.message.from) ^ SyntaxError: invalid syntax
请问如何访问from块内的字段?
解决方法
from是Python的关键字,无法直接通过.运算符访问对应的属性,以下是几种可行的解决方式:
方式1:使用getattr()函数动态获取属性
getattr()可以绕过关键字限制,动态读取属性:
# 获取整个from对象 from_obj = getattr(x.message, 'from') print(from_obj.first_name) # 直接读取from对象内的字段 print(getattr(x.message, 'from').id)
方式2:解析JSON时重命名冲突属性
在自定义的object_hook里把关键字属性替换成合法名称,比如将from改为from_user:
def json_to_namespace(d): # 处理关键字冲突 if 'from' in d: d['from_user'] = d.pop('from') return SimpleNamespace(**d) x = json.loads(data, object_hook=json_to_namespace) # 直接用新名称访问 print(x.message.from_user.username)
方式3:改用字典形式解析JSON
如果不需要命名空间对象,直接用默认的字典解析,通过键名访问即可:
x = json.loads(data) print(x['message']['from']['language_code'])
内容的提问来源于stack exchange,提问作者vasopicasso
相关产品推荐
相关产品推荐

