我有一個 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 錯誤。period在 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 字串是否正確?
uj5u.com熱心網友回復:
這些引號表明它是一個字串。它在傳輸資料中顯示為字串,因為它是payload.
如果您使用某些東西將有效負載轉換為 JSON 以進行傳輸,請不要對“句點”部分進行預編碼。如果這樣做,JSON 格式化程式會將整個部分編碼為字串,而不是物件和陣列。相反,使用 Python 字典和陣列并讓 JSON 格式化程式處理轉換。
payload = {
"period": {
'p1': [{
'type': 'D',
'start': start_period,
'end': end_period
}]
},
"max-results": 50,
"page-num": 1,
"options": {},
}
json.dumps(payload)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/471998.html
標籤:python-3.x 字典 大括号 f弦
上一篇:將嵌套字典的值標準化為[0,1]
下一篇:組合兩個行串列
