You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 15:00:46