lets say i have a payload which i am using to hit my API
JavaScript
x
5
1
payload = json.dumps({"from_date":"2019-10-10",
2
"from_date":"2019-10-12",
3
"pg_no": 1,
4
"idx": "fsdf"})
5
but i wanted to make its pg_no
value as dynamic using for loop i.e.
JavaScript
1
8
1
payload = json.dumps({"from_date":"2019-10-10",
2
"from_date":"2019-10-12",
3
"pg_no": {},
4
"idx": "fsdf"})
5
6
for i in range(1,5):
7
payload.format(i)
8
getting this error
JavaScript
1
7
1
KeyError Traceback (most recent call last)
2
<ipython-input-7-5b565a97da5e> in <module>
3
1 for i in range(1,5):
4
----> 2 payload.format(i)
5
6
KeyError: '"from_date"'
7
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
JavaScript
1
9
1
data = {'rom_date':'2019-10-10',
2
'fom_date':'2019-10-12',
3
'pg_no': {},
4
'idx': 'fsdf'}
5
6
for i in range(1,5):
7
data['pg_no'] = i
8
print(json.dumps(data))
9