【发布时间】:2019-12-23 06:21:31
【问题描述】:
我正在努力找出循环函数的最佳方法。这个 API 的输出是一个图形连接,我有点不在我的元素中。我真的需要从 api 输出中获取 ID,并将它们以字典或某种形式传递给另一个 API 调用。
**** 重要的是要注意原始输出是图形连接.... print(type(api_response) 确实将其显示为列表,但是,如果我执行 print(type(api_response[0] )) 它返回一个
这是 api 调用的原始输出:
[{'_from':无,'to':{'id':'5c9941fcdd2eeb6a6787916e','type':'user'}},{'_from':无,'to':{'id': '5cc9055fcc5781152ca6eeb8', 'type': 'user'}}, {'_from': None, 'to': {'id': '5d1cf102c94c052cf1bfb3cc', 'type': 'user'}}]
这是我到目前为止的代码.....
api_response = api_instance.graph_user_group_members_list(group_id, content_type, accept,limit=limit, skip=skip, x_org_id=x_org_id)
def extract_id(result):
result = str(result).split(' ')
for i, r in enumerate(result):
if 'id' in r:
id = (result[i+1].translate(str.maketrans('', '', string.punctuation)))
print( id )
return id
extract_id(api_response)
def extract_id(result):
result = str(result).split(' ')
for i, r in enumerate(result):
if 'id' in r:
id = (result[i+8].translate(str.maketrans('', '', string.punctuation)))
print( id )
return id
extract_id(api_response)
def extract_id(result):
result = str(result).split(' ')
for i, r in enumerate(result):
if 'id' in r:
id = (result[i+15].translate(str.maketrans('', '', string.punctuation)))
print( id )
return id
extract_id(api_response)
我已经能够使用函数来提取 ID,但我是通过字符串来提取的。我需要一个可扩展的解决方案,我可以使用它来将这些 ID 传递给另一个 API 调用。
我尝试使用 for 循环,但因为它是 1 个字符串并且 i+1 定义了 id 的位置,所以它是多余的,并且只输出 id 的 1 次。
我使用这些功能中的每一个都收到了正确的输出,但是,它不可扩展......而且不是解决方案。请帮助指导我......
【问题讨论】:
标签: python json python-3.x string api