[英]Format Request Payload in a loop
我試圖通過執行相同的請求 12 次來循環處理 API 請求:
這是請求的有效載荷部分,這有效:
payload="{\n\t\"filter\": {\n \"year\":2020,\n \"month\":10,\n\t\t\"customer_id\":52\n\t},\n \"sort\":{\"_id.date\":1}\n}"
我的目標是通過在月后添加循環變量“mes”來格式化有效負載字符串。 據我了解,我嘗試使用:
for mes in range(0,12):
payload="{\n\t\"filter\": {\n \"year\":2020,\n \"month\":
{mes},\n\t\t\"customer_id\":52\n\t},\n \"sort\":{\"_id.date\":1}\n}".format(mes=mes)
但是不工作,我如何格式化它以便我可以遍歷有效負載? 什么是解決方案?
謝謝
當您使用.format()
時,您不能在 str 中包含{}
,因為它們將被識別為將 str 放入.format()
的位置。 您需要在不打算使用格式化 str 的地方將它們中的每一個加倍:
for mes in range(0,12):
payload="{{\n\t\"filter\": {{\n \"year\":2020,\n \"month\"{mes},\n\t\t\"customer_id\":52\n\t}},\n \"sort\":{{\"_id.date\":1}}\n}}".format(mes=mes)
簡而言之, '{a} {something else}'.format(a=1)
不起作用,但'{a} {{something else}}'.format(a=1)
起作用並打印為'1 {something else}'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.