【问题标题】:Looping through a function循环一个函数
【发布时间】: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


    【解决方案1】:

    因此,要将响应作为字符串问题解决,我建议使用 python 的builtin json module。具体来说,.loads() 方法可以将字符串转换为字典或字典列表。从那里您可以遍历列表或字典并检查键是否等于'id'。这是一个基于您所说的响应的示例。

    import json
    
    s = "[{'_from': None, 'to': {'id': '5c9941fcdd2eeb6a6787916e', 'type': 'user'}}, {'_from': None, 'to': {'id': '5cc9055fcc5781152ca6eeb8', 'type': 'user'}}, {'_from': None, 'to': {'id': '5d1cf102c94c052cf1bfb3cc', 'type': 'user'}}]"
    
    # json uses double quotes and null; there is probably a better way to do this though
    s = s.replace("\'", '\"').replace('None', 'null') 
    
    response = json.loads(s)  # list of dicts
    
    for d in response:
        for key, value in d['to'].items():
            if key == 'id':
                print(value)  # or whatever else you want to do
    
                # 5c9941fcdd2eeb6a6787916e
                # 5cc9055fcc5781152ca6eeb8
                # 5d1cf102c94c052cf1bfb3cc
    
    

    【讨论】:

    • 我之前尝试过使用 json.loads 来解决这个问题,然后又试了一次。我收到此错误 TypeError: the JSON object must be str, bytes or bytearray, not list
    • 这实际上可能很棒! list 的内容有哪些类型?字典还是字符串?如果它们是字典,那么您可以直接跳到 for 循环。
    • 同意,但是当我直接跳到 for 循环时出现不可序列化的错误。不过,我感谢您,因为我接受了您在将 json sring 加载到 json.loads 之前修复它的建议。
    猜你喜欢
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 2021-01-18
    相关资源
    最近更新 更多