lets say i have a payload which i am using to hit my API
payload = json.dumps({"from_date":"2019-10-10",
"from_date":"2019-10-12",
"pg_no": 1,
"idx": "fsdf"})
but i wanted to make its pg_no value as dynamic using for loop i.e.
payload = json.dumps({"from_date":"2019-10-10",
"from_date":"2019-10-12",
"pg_no": {},
"idx": "fsdf"})
for i in range(1,5):
payload.format(i)
getting this error
KeyError Traceback (most recent call last)
<ipython-input-7-5b565a97da5e> in <module>
1 for i in range(1,5):
----> 2 payload.format(i)
KeyError: '"from_date"'
Advertisement
Answer
first in your dictionary you are using same key from_data which is gonna be only last one present there.
second main problem is causing by { bracket format use this place variable if you want to parse single single { then you have to use {{ in string
. so simple put value in dictionary then convert to string like this
data = {'rom_date':'2019-10-10',
'fom_date':'2019-10-12',
'pg_no': {},
'idx': 'fsdf'}
for i in range(1,5):
data['pg_no'] = i
print(json.dumps(data))