Home > Back-end >  Loop through body content - Python
Loop through body content - Python

Time:08-15

How would I go about looping through calendarID found in the body of the below API call. Would like to add a addition of 1 each time until no data is found.

import requests
import json

url = "http://apiurl/collectionData"

payload = json.dumps({
  "calendarID": "363,365,366,367,368",
  "businessDirectoryID": "36,37"
})
headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Basic abcdeMzYxQUMyN0NGNTJBNDZEQi'
}

response = requests.request("POST", url, headers=headers, data=payload)

data = json.loads(response.text)

with open('How_Waste.json', 'w') as json_file:
    json.dump(data, json_file, indent=4)

CodePudding user response:

Use split() to create a list of your numbers, convert those into integers, add 1 to your numbers, convert it back to a string and add it back to the list.

# before `json.dumps()`

payload = {
  "calendarID": "363,365,366,367,368",
  "businessDirectoryID": "36,37"
}
print(f"before: {payload}")

# `split()` to create a list of your numbers
nums = payload["calendarID"].split(",")
for i, num in enumerate(nums):
    # convert to int and add 1
    num = int(num)   1
    # convert to str and add back to list
    nums[i] = str(num)

# join the list to create a str, separated from commas
payload["calendarID"] = ",".join(nums)
print(f"after: {payload}")

Output

before: {'calendarID': '363,365,366,367,368', 'businessDirectoryID': '36,37'}
after: {'calendarID': '364,366,367,368,369', 'businessDirectoryID': '36,37'}

CodePudding user response:

Looks like you have a string of integers each separated by comma and you want to add 1 to each of the values and represent as a new string.

Therefore:

cid = "363,365,366,367,368"

cid = ','.join((cid, str(int(cid.split(',')[-1]) 1)))

print(cid)

Output:

363,365,366,367,368,369
  • Related