我需要从for循环中获取多个值并将其传递给api调用。对我来说最好的方法是什么?
被引用的值是'id',我将需要每个值来填充api调用中的id要求。
*** MY for循环
response = json.loads(z)
for d in response:
for key, value in d['to'].items():
if key == 'id':
print(value)
*** API调用
id = '' # str |
content_type = 'application/json' # str | (default to application/json)
accept = 'application/json' # str | (default to application/json)
fields = '' # str | Use a space seperated string of field parameters to include the data in the response. If omitted, the default list of fields will be returned. (optional) (default to )
filter = 'filter_example' # str | A filter to apply to the query. (optional)
x_org_id = '' # str | (optional) (default to )
api_response = api_instance.systemusers_get(id, content_type, accept, fields=fields, filter=filter, x_org_id=x_org_id)
答案 0 :(得分:1)
正如您指出的那样,您需要一个字符串。因此,当您遍历它们时,必须将它们添加到某些字符串中。因此,让我们从仅创建一个空字符串开始。然后,当我们循环时,我们可以将连接到字符串
,而不是打印ID。string = ""
for d in response:
for key, value in d['to'].items():
if key == 'id':
string += value
,然后再更新
:id = string
现在,我当然不知道该字符串对于特定的API需要采用什么格式。但是您应该能够调整模式,例如,如果需要的话,用逗号分隔值。
(注意,在这个问题的上下文中,我使用了名称字符串,但很明显要提供一个更好的变量名称)
编辑:如何进行多个API调用
如果每个API调用只能发送一个ID,那么您可以做两件事。也可以在循环中进行呼叫,或将此ID保存到列表中。无论哪种情况,如果将API调用包装到一个函数中都会有帮助:
def make_api_call(id)
id = id
content_type = 'application/json' # str | (default to application/json)
accept = 'application/json' # str | (default to application/json)
fields = '' # str | Use a space seperated string of field parameters to include the data in the response. If omitted, the default list of fields will be returned. (optional) (default to )
filter = 'filter_example' # str | A filter to apply to the query. (optional)
x_org_id = '' # str | (optional) (default to )
api_response = api_instance.systemusers_get(id, content_type, accept, fields=fields, filter=filter, x_org_id=x_org_id)
现在,您可以像这样在循环中调用它:
for d in response:
for key, value in d['to'].items():
if key == 'id':
make_api_call(value)
或者您可以建立一个列表,然后在该列表上运行呼叫:
all_ids = []
for d in response:
for key, value in d['to'].items():
if key == 'id':
all_ids.append(value)
for id in all_ids:
make_api_call(id)
(注意,我正在使用变量名'id'来解决问题。但是,最好使用'_id',因为'id'是内置变量。)