我想與Coinbase的API合作,並希望將它們的價格用作浮動,但該對象返回一個API對象,我不知道如何轉換它。Python coinbase API的價格浮動
例如,如果我稱之爲client.get_spot_price()
將返回此:
{
"amount": "316.08",
"currency": "USD"
}
我只想316.08
。我該如何解決它?
我想與Coinbase的API合作,並希望將它們的價格用作浮動,但該對象返回一個API對象,我不知道如何轉換它。Python coinbase API的價格浮動
例如,如果我稱之爲client.get_spot_price()
將返回此:
{
"amount": "316.08",
"currency": "USD"
}
我只想316.08
。我該如何解決它?
data = {
"amount": "316.08",
"currency": "USD"
}
price = float(text['amount'])
隨着API的使用JSON解析器
import json
data = client.get_spot_price()
price = float(json.loads(data)['amount'])
print price
它看起來像一個json
輸出。你可以在Python導入json
庫,並使用loads
方法讀它,樣品:
import json
# get data from the API's method
response = client.get_spot_price()
# parse the content of the response using json format
data = json.loads(response)
# get the amount and convert to float
amount = float(data['amount'])
print(amount)
起初,你把你返回的對象到變量和檢查返回值的類型。 只是這樣的:
打印類型(your_returned對象/變量)
如果這是詞典可以從字典經由字典鍵訪問數據。字典的結構是:
字典= {key_1:_1,key_2:_2,...... key_n:value_n}
1.You可以訪問字典的所有值。 象下面這樣:
打印的dict [key_1] #output將返回值_1
INT(your_data) 轉換爲float: 浮動(your_data)
如果不是,你需要將其轉換爲一個字典或JSON字典通過:
json.loads(你返回的對象)
在你的情況,你可以這樣做:
variable = client.get_spot_price()
print type(variable) #if it is dictionary or not
print float(variable["amount"]) #will return your price in float
由於第一種方法的工作原理,甚至當我稱之爲「價格=浮動(文本[」量「])」與售價的API對象時,它的偉大工程。 – ctrigose
第一種方法在這裏工作,因爲這裏的API響應非常簡單,只有兩個值。例如,twitter在其API響應中包含更多數據,並且在使用JSON解析之後輕鬆收集數據。 – Harwee