代码之家  ›  专栏  ›  技术社区  ›  William

从JSON响应中提取浮点键对值时发生TypeError

  •  0
  • William  · 技术社区  · 3 年前

    背景 我有一个函数,它接受一个名为 api_response (其本身使用格式化 api_response = json.loads(response.text) 从另一个函数中提取2个密钥对值,即 id percent_complete 并打印它们。

    作用 -

    def unpack_response():
        api_response = api_call()
    # Code Block # 1
        while "meta" not in api_response:
            id_value = "id"
            res1 = [val[id_value] for key, val in api_response.items() if id_value in val]
            id_value = "".join(res1)
            percent_value = "percent_complete"
            # The following line of code is referenced in the TypeError  
            res2 = [val['attributes'][percent_value] for key, val in api_response.items() if percent_value in val['attributes']]
            percent_value = "".join(res2)
            print(f' Your data requested, associated with ID: {id_value} is {percent_value} complete!')
            time.sleep(5)
            continue
    # Code Block # 2
        if "meta" in api_response:
            print(api_response)
    unpack_response()
    

    JSON响应( api_响应 ) -

    {'data': {'id': '2205853', 'type': 'jobs', 'attributes': {'job_type': 'PORTFOLIO_VIEW_RESULTS', 'started_at': '2021-12-17T02:53:48Z', 'parameters': {'end_date': '2021-12-14', 'output_type': 'json', 'view_id': 304078, 'portfolio_id': 1, 'portfolio_type': 'firm', 'start_date': '2021-12-14'}, 'percent_complete': 0.19, 'status': 'In Progress'}, 'relationships': {'creator': {'links': {'self': '/v1/jobs/2205853/relationships/creator', 'related': '/v1/jobs/2205853/creator'}, 'data': {'type': 'users', 'id': '731221'}}}, 'links': {'self': '/v1/jobs/2205853'}}, 'included': []}
    

    问题 -该函数返回 身份证件 键值对,无问题并打印(前提是我删除所有 完成百分比 -相关代码),但是 "percent_complete" 密钥对值导致以下情况 TypeError .

    错误 -

    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-38-8a61597dcee6> in <module>
         16     if "meta" in api_response:
         17         print(api_response)
    ---> 18 unpack_response()
    
    <ipython-input-38-8a61597dcee6> in unpack_response()
          8         percent_value = "percent_complete"
          9 #         res2 = [val['attributes'][percent_value] for key, val in api_response.items() if percent_value in val['attributes']]
    ---> 10         res2 = [val['attributes'].get(percent_value, '') for key, val in api_response.items()]
         11         percent_value = "".join(res2)
         12         print(f' Your data requested, associated with ID: {id_value} is {percent_value} complete!')
    
    <ipython-input-38-8a61597dcee6> in <listcomp>(.0)
          8         percent_value = "percent_complete"
          9 #         res2 = [val['attributes'][percent_value] for key, val in api_response.items() if percent_value in val['attributes']]
    ---> 10         res2 = [val['attributes'].get(percent_value, '') for key, val in api_response.items()]
         11         percent_value = "".join(res2)
         12         print(f' Your data requested, associated with ID: {id_value} is {percent_value} complete!')
    
    TypeError: list indices must be integers or slices, not str
    

    有人能帮我理解为什么 身份证件 无问题退货(前提是我删除所有 完成百分比 -相关代码),并且的密钥对值 完成百分比 没有。这与密钥对值是浮点值有关吗?

    0 回复  |  直到 3 年前
        1
  •  0
  •   William    3 年前

    感谢众多评论(谢谢 Barmar rchrome ),我把函数重写如下-

    def unpack_response():
        api_response = api_call()
        if "meta" not in api_response:
            id_value = "id"
            res1 = [val[id_value] for key, val in api_response.items() if id_value in val]
            id_value = "".join(res1)
            percent_value = "percent_complete"
            res2 = api_response["data"]["attributes"].get("percent_complete", '')
            print(f' Your data requested, associated with ID: {id_value} is {res2} complete!')
            time.sleep(5)
            api_response = api_call()
        if not "meta" in api_response:
            print(api_response)
    unpack_response()