user14822876
user14822876

Reputation: 11

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

Upvotes: 1

Views: 151

Answers (1)

Z Li
Z Li

Reputation: 4318

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}'

Upvotes: 1

Related Questions