簡體   English   中英

如何從 python、Django 中的 api 做出的 json 響應中提取數據

[英]How to extract data from json response made by an api in python, Django

我正在創建費用,我想從中獲取其“hosted_url”以便從頁面重定向用戶。

我正在嘗試從 json 中提取它,但我是新手,不知道如何提取

        ...
        url = "https://api.commerce.coinbase.com/charges"

        payload = {
            "local_price": {
                "amount": 1,
                "currency": USDT
            },
            "name": "Test for fun",
            "description": "Project 2",
            "pricing_type": "fixed_price"
        }
        headers = {
            "accept": "application/json",
            "X-CC-Version": "2018-03-22",
            "X-CC-Api-Key" : "**********",
            "content-type": "application/json"
        }

        response = requests.post(url, json=payload, headers=headers)

        print(response.text)

這是向 api 發出請求以創建費用的代碼,在 JSON 響應中我得到以下字段:

{
   "data":{
       "code": "123DVAS",
       "hosted_url": "https://commerce.coinbase.com/charges/123DVAS",
       ...
   }
}

我想以某種方式將此消息“123DVAS”放入變量中或進行如下重定向:

return render(request, 'https://commerce.coinbase.com/charges/123DVAS')

你可以這樣做:

# Suppose it's your response looks like this
response = {"hosted_url": "https://commerce.coinbase.com/charges/123DVAS"}
id_fecthed = response.get('hosted_url').split('/')[-1]

# You can redner like this
render(request, f'https://commerce.coinbase.com/charges/{id_fecthed}')

# If you sure that always you want to redirect to hosted_url
# Then you can use this
render(request, response.get('hosted_url'))

編輯:

從請求中讀取數據的完整代碼。

import json

response = requests.post(url, json=payload, headers=headers)
data = json.loads(response.text)
hosted_url = data.get("data",{}).get('hosted_url')
if hosted_url:
    id_fecthed = hosted_url.split('/')[-1]
    return redirect(f'https://commerce.coinbase.com/charges/{id_fecthed}')
else:
    print('Host URL not available')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM