我正在寻找使用.format()或其他方法,该方法允许我将参数传递给Python中的JSON查询。我已经在Python中使用SQL以及在诸如将参数传递到网站链接上之类的东西使用.format()了。理想情况下,我希望能够在一开始就定义查询中的任何变量。如果有的话,我只是想了解为什么.format()在这里不起作用。
我已经搜索了很多,还没有找到具体针对此确切问题的示例,因此如果这很明显,我们深表歉意。
这是尝试使用.format()时返回的错误:
Traceback (most recent call last):
File "rti3.py", line 25, in <module>
}""".format(adgroup)
KeyError: '\n\t\t\t\t"category1"'
这是我的代码:
#!/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)
答案 0 :(得分:0)
一种方法是加载json字符串并进行必要的更改。这全都与格式化内容有关。
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)
输出
'{"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"]}]}'
答案 1 :(得分:0)
.format()
不起作用,因为字符串中的所有{...}
表达式都被解释为格式说明符。可以通过加倍花括号并为{{...}}
以外的所有字母写{campaignid}
来解决此问题,但是在您的特定情况下,最好完全放弃使用.format()
。相反,只需将JSON编写为本地Python对象:
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": []
}
,然后使用json.dumps
将其转换为字符串:
data = 'query=' + json.dumps(query_data)
答案 2 :(得分:0)
尝试将数据存储为字典而不是格式字符串。
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))
输出:
{"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": []}}