I have a following block of code:
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
)
Which works fine. However, when I add
print(x.message.from)
I get an error:
File "<ipython-input-179-dec1b9f9affa>", line 1
print(x.message.from)
^
SyntaxError: invalid syntax
Could you please help me? How can I access fields inside 'from' block?
CodePudding user response:
You can access the fields inside the from block by using square bracket notation instead of dot notation. Here is how your code would look with the changes:
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"])
In Python, you use square bracket notation []
to access dictionary keys, and dot notation .
to access object attributes. In this case, from
is a reserved keyword in Python, so you cannot use dot notation to access it directly. Instead, you must use square bracket notation to access it.
(ChatGPT AI assisted with this answer)
CodePudding user response:
As from
is a keyword, try this x.message.__getattribute__('from')
:
>>> x.message.__getattribute__('from')
namespace(last_name='test_l_name',
is_bot=False,
username='test_username',
id=134839552,
first_name='test_name',
language_code='en')
And to get one of its attribute, say username
, you could access like what you have been doing:
>>> x.message.__getattribute__('from').username
'test_username'