简体   繁体   中英

Format Request Payload in a loop

I am trying to loop on an API request by doing the same request 12 times:

this is the payload part of the request, this works:

    payload="{\n\t\"filter\": {\n        \"year\":2020,\n        \"month\":10,\n\t\t\"customer_id\":52\n\t},\n    \"sort\":{\"_id.date\":1}\n}"

My goal is to format the payload string by adding the looped variable "mes" after month. As far as I understand I tried to use:

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)

But is not working, how can I format it so I can loop through the Payload? What could be a solution?

Thank you

When you are using .format() you cannot have {} in the str as they will be recognized as the place to put the str in .format() . You need to double each one of them where you do not intend to use formatted 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)

In short, '{a} {something else}'.format(a=1) does not work but '{a} {{something else}}'.format(a=1) works and gets printed as '1 {something else}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM