python f-string未正确格式化变量的dict
我有一个API呼叫的有效载荷,例如:
start_period = "2022-05-02"
end_period = "2022-05-02"
payload = {"period": f"{{'p1': [{{'type': 'D', 'start': '{start_period}', 'end': '{end_period}'}}]}}",
"max-results": 50,
"page-num": 1,
"options": {}
}
当我发送此有效载荷时,我会检索HTTP 403错误。有效载荷的期间
在pycharm中调试时看起来像:
'{\'p1\': [{\'type\': \'D\', \'start\': \'2022-05-02\', \'end\': \'2022-05-02\'}]}'
dict本身内(再次在pycharm调试器中):
{'period': "{'p1': [{'type': 'D', 'start': '2022-05-02', 'end': '2022-05-02'}]}", 'max-results': 50, 'page-num': 1, 'options': {}}
它应该像这样:
{"period": {"p1": [{"type": "D", "start": "2022-05-02", "end": "2022-05-02"}]}, "max-results": 50, "page-num": 1, 'options': {}}
或在 我不确定单引号是否在抛出此错误。我目前的F串是否正确?
I have a payload for an API call, like so:
start_period = "2022-05-02"
end_period = "2022-05-02"
payload = {"period": f"{{'p1': [{{'type': 'D', 'start': '{start_period}', 'end': '{end_period}'}}]}}",
"max-results": 50,
"page-num": 1,
"options": {}
}
When I send this payload, I retrieve a HTTP 403 error. The payload's period
when debugging in PyCharm looks like:
'{\'p1\': [{\'type\': \'D\', \'start\': \'2022-05-02\', \'end\': \'2022-05-02\'}]}'
or within the dict itself (again in PyCharm Debugger):
{'period': "{'p1': [{'type': 'D', 'start': '2022-05-02', 'end': '2022-05-02'}]}", 'max-results': 50, 'page-num': 1, 'options': {}}
It should look like this:
{"period": {"p1": [{"type": "D", "start": "2022-05-02", "end": "2022-05-02"}]}, "max-results": 50, "page-num": 1, 'options': {}}
(note the extra quotation marks wrapping around the entire period). I'm not sure if the single quotations are throwing this error. Is my current f-string correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这些引号表明这是一个字符串。它是传输数据中的字符串,因为它是
有效载荷
中的字符串。如果您正在使用某些内容将有效载荷转换为JSON进行转移,请不要预先编码“周期”部分。如果这样做,则JSON格式化器将将整个部分编码为字符串,而不是对象&数组。相反,使用python dicts&阵列,让JSON格式处理转换。
Those quotes indicate it's a string. It's appearing as a string in the transfer data because it's a string in
payload
.If you're using something to convert the payload to JSON for transfer, don't pre-encode the "period" portion. If you do, the JSON formatter will then encode that entire portion as a string, rather than as objects & arrays. Instead, use Python dicts & arrays and let the JSON formatter handle the conversion.