繁体   English   中英

从 Python 中的 JSON 文件中提取浮点数

[英]Extracting float from JSON file in Python

背景 -
我有一个 function 返回 API 响应。 如果api_response包含meta它将打印响应,否则 function 循环通过一些提取和打印idpercent_complete密钥对值的代码。 其目的是 API 响应将返回这些值,以显示用户可以单独调用数据有多接近。

问题- 虽然返回和打印id没有问题,但percent_complete返回空白。

Function -

def unpack_response():
    api_response = api_call()
# Code Block # 1
    while "meta" not in api_response:
        id_value = "id"
        res = [val[id_value] for key, val in api_response.items() if id_value in val]
        id_value = "".join(res)
        percent_value = "percent_complete"
        res = [val[percent_value] for key, val in api_response.items() if percent_value in val]
        percent_value = "".join(res)
        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)

示例打印 output - 显示当前每次循环迭代打印的内容的示例:

Your data requested, associated with ID: 2205686 is  complete!

API 响应- 我成功提取id密钥对值的响应示例,但是percent_complete密钥对值为空白:

{'data': {'id': '2205686',
  'type': 'jobs',
  'attributes': {'job_type': 'PORTFOLIO_VIEW_RESULTS',
   'started_at': '2021-12-16T18:59:50Z',
   '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/2205679/relationships/creator',
     'related': '/v1/jobs/2205679/creator'},
    'data': {'type': 'users', 'id': '731221'}}},
  'links': {'self': '/v1/jobs/2205679'}},
 'included': []}

我的想法- 与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"
   #         res2 = [val['attributes'][percent_value] for key, val in api_response.items() if percent_value in val['attributes']]
           res2 = [val['attributes'].get(percent_value, '') for key, val in api_response.items()]
           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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM