[英]How can I use list values to format an API payload request string?
I'm trying to make multiple look-ups using an API using a list in order to create a dictionary that I can then manipulate a dataframe with.我正在尝试使用 API 使用列表进行多次查找,以便创建一个字典,然后我可以使用该字典操作 dataframe 。 I am currently using ({}.format(i)), which runs, however I receive a warning from the API that there is an invalid format for the required field.
我目前正在使用 ({}.format(i)),它正在运行,但是我收到来自 API 的警告,指出必填字段的格式无效。
When I test the code by hand typing one of the list values in place of ({}.format(i)), it works, so I 'm fairly sure it's related to using ({}.format(i)), however, not sure of another way to do this.当我通过手动键入列表值之一代替 ({}.format(i)) 来测试代码时,它可以工作,所以我很确定它与使用 ({}.format(i)) 相关,但是,不确定另一种方法来做到这一点。
I've included an example of the code below.我在下面包含了一个代码示例。 Is it the " being escaped by the backslash? Thanks for any help!
是 " 被反斜杠转义了吗?感谢您的帮助!
list_string = ['XXXXXX','YYYYYY','ZZZZZZ']
for i in list_string
url = "https://fakeurl.api.co.uk/enquiry"
payload = "{\n\t\"identification1\": \"({}.format(i))\"\n}" # Works when ({}.format(i)) replaced with XXXXXX
headers = {
'x-api-key': 'INSERT KEY HERE',
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data = payload)
response = response.json()
response
The format
call needs to be added at the end of the string, like the following.需要在字符串末尾添加
format
调用,如下所示。 Also, list
is a reserved word in Python, please use a different one.另外,
list
是 Python 中的保留字,请使用不同的。 And, you need to escape the outer curly braces.而且,您需要转义外部花括号。
EDIT: Removed brackets after adding additional curly braces.编辑:添加额外的花括号后删除括号。
list_string = ['XXXXXX','YYYYYY','ZZZZZZ']
for i in list_string:
url = "https://fakeurl.api.co.uk/enquiry"
payload = "{{\n\t\"identification1\": \"{}\"\n}}".format(i)
headers = {
'x-api-key': 'INSERT KEY HERE',
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data = payload)
response = response.json()
response
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.