I am looking to use .format(), or another method, that would allow me to pass parameters to a JSON query in my Python. I've used .format() using SQL in Python as well as for things such as passing parameters onto website links. Ideally, I'd like to be able to define any one of the variables in the query at the beginning. If anything, I'd simply like to understand WHY .format() doesn't work here.
I've searched quite a bit and have not found an example specific to this exact problem so apologies if this seems obvious.
This is the error it returns when attempting to use .format():
Traceback (most recent call last):
File "rti3.py", line 25, in <module>
}""".format(adgroup)
KeyError: '\n\t\t\t\t"category1"'
This is my code:
#!/usr/bin/python
import os.path
import requests
import sys
import json
campaignid = 0
data = """query={
"category1": "",
"kpi_or": false,
"campaign_id": {campaignid},
"pub_bid_rates":1000,
"creatives": [{"creative_type":"video",
"banner_size":"320x250"}],
"geotargets": [{"type":6,"value":["us"]}],
"target_profiles": [],
"publishers": []
}""".format(campaignid)
def avails():
req = 'http://****.****.***.com:****/API'
resp = requests.post(req, data).json()
if 'adgroups' not in resp:
return 0
else:
return int(resp['adgroups'][0]['reach'])
def main(progname, argv):
print(avails())
if __name__ == '__main__':
try:
main(sys.argv[0], sys.argv[1:])
except Exception as err:
print('Caught exception:', err)
sys.exit(1)