我正在尝试通过Python 3.8建立对Google Calendar API的忙/闲请求。但是,当我尝试将新项目插入到body请求中时,我收到了错误的请求,无法使用它。
此代码有效:
SUBJECTA = '[email protected]'
SUBJECTB = '[email protected]'
body = {
"timeMin": now,
"timeMax": nownext,
"timeZone": 'America/New_York',
"items": [{'id': SUBJECTA},{"id": SUBJECTB} ]
}
良好的身体成绩:
{'timeMin': '2019-11-05T11:42:21.354803Z',
'timeMax': '2019-11-05T12:42:21.354823Z',
'timeZone': 'America/New_York',
'items': [{'id': '[email protected]'},
{'id': '[email protected]'}]}
但是,在使用此代码时:
items = "{'ID': '[email protected]'},{'ID': '[email protected]'},{'ID': '[email protected]'}"
body = {
"timeMin": now,
"timeMax": nownext,
"timeZone": 'America/New_York',
"items": items
}
正文结果在开始和结束位置都包含其他引号,导致请求失败:
{'timeMin': '2019-11-05T12:04:41.189784Z',
'timeMax': '2019-11-05T13:04:41.189804Z',
'timeZone': 'America/New_York',
'items': ["{'ID': [email protected]},{'ID':
[email protected]},{'ID':
[email protected]},{'ID':
[email protected]},{'ID':
[email protected]}"]}
处理它并以正确的方式发送项目清单的正确方法是什么?
items
由字符串给出"{'ID': '[email protected]'},{'ID': '[email protected]'},{'ID': '[email protected]'}"
。[{'ID': '[email protected]'}, {'ID': '[email protected]'}, {'ID': '[email protected]'}]
。如果我的理解是正确的,那么这个答案呢?请认为这只是几个答案之一。
import json # Added
items = "{'ID': '[email protected]'},{'ID': '[email protected]'},{'ID': '[email protected]'}"
items = json.loads(("[" + items + "]").replace("\'", "\"")) # Added
body = {
"timeMin": now,
"timeMax": nownext,
"timeZone": 'America/New_York',
"items": items
}
print(body)
如果now
和nownext
是的值"now"
和"nownext"
分别,结果如下。
{
"timeMin": "now",
"timeMax": "nownext",
"timeZone": "America/New_York",
"items": [
{
"ID": "[email protected]"
},
{
"ID": "[email protected]"
},
{
"ID": "[email protected]"
}
]
}
如果可以将ID作为字符串值检索,则建议使用以下方法作为示例脚本。
ids = ['[email protected]', '[email protected]', '[email protected]']
items = [{'ID': id} for id in ids]
如果我误解了您的问题,而这不是您想要的结果,我深表歉意。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句