Python 带有变量的 dict 的 f 字符串格式不正确

Python f-string not formatted correctly for dict with variables

我有一个 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 中调试时有效载荷的 period 看起来像:

'{\'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-string 正确吗?

那些引号表明它是一个字符串。它在传输数据中显示为字符串,因为它是 payload.

中的字符串

如果您使用某些东西将有效负载转换为 JSON 以进行传输,请不要 pre-encode “句点”部分。如果这样做,JSON 格式化程序会将整个部分编码为字符串,而不是对象和数组。相反,使用 Python 字典和数组并让 JSON 格式化程序处理转换。

payload = {
    "period": {
        'p1': [{
            'type': 'D',
            'start': start_period,
            'end': end_period
        }]
    },
    "max-results": 50,
    "page-num": 1,
    "options": {},
}

json.dumps(payload)