0

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)

3 Answers 3

1

.format() isn't working because all of the {...} expressions in the string are being interpreted as format specifiers. This could be fixed by doubling the braces and writing {{...}} for all but the {campaignid}, but in your specific case, it would be a much better idea to forgo the use of .format() entirely. Instead, just write the JSON as a native Python object:

query_data = {
    "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": []
}

and then use json.dumps to convert it to a string:

data = 'query=' + json.dumps(query_data)
Sign up to request clarification or add additional context in comments.

Comments

0

One way could be to load the json string and make the necessary changes. It is all about formatting stuff.

import json
campaignid = 0

data = json.loads("""{"category1": "","kpi_or": false,"campaign_id": {},"pub_bid_rates":1000,"creatives": [{"creative_type":"video", "banner_size":"320x250"}],"geotargets": [{"type":6,"value":["us"]}],"target_profiles": [],"publishers": []}""")
data['campaign_id']=campaignid
json.dumps(data)

Output

'{"category1": "", "kpi_or": false, "publishers": [], "campaign_id": 0, "creatives": 
[{"banner_size": "320x250", "creative_type": "video"}], 
"target_profiles": [], "pub_bid_rates": 1000, "geotargets": [{"type": 6, "value": ["us"]}]}'

Comments

0

Try storing your data as a dictionary instead of as a format string.

data = {"query": {"category1": "",
                  "kpi_or": False,
                  "campaing_id": campaignid,
                  "pub_bid_rates": 1000,
                  "creatives": [{"creative_type": "video",
                                 "banner_size": "320x250"}],
                  "geotargets": [{"type": 6,
                                  "value": ["us"]}],
                  "target_profiles": [],
                  "publishers": []}}

print(json.dumps(data))

Output:

{"query": {"category1": "", "kpi_or": false, "campaing_id": 0, "pub_bid_rates": 1000, "creatives": [{"creative_type": "video", "banner_size": "320x250"}], "geotargets": [{"type": 6, "value": ["us"]}], "target_profiles": [], "publishers": []}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.