簡體   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