Python Coinbase API Prices as Floating

I am trying to work with the Coinbase API and would like to use their prices as a float, but the object returns an API object and I don’t know how to convert it.

For example, if I call client.get_spot_price(), it will return this:

{
  "amount": "316.08", 
  "currency": "USD"
}

And I just want to 316.08. How can I solve it?

+4
source share
3 answers
data = {
  "amount": "316.08", 
  "currency": "USD"
}
price = float(text['amount'])

API uses JSON parser

import json
data = client.get_spot_price()
price = float(json.loads(data)['amount'])
print price
+1
source

He looks like json. You can import the library jsoninto python and read it using the method loads, for the sample:

import json

# get data from the API 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)
0
source

. :

(_ /)

, . :

dict = {key_1: value_1, key_2: value_2,...... key_n: value_n}

1. . :

print dict [key_1] #output will be returned value_1

  1. Then you can convert the returned data to integer or float. To convert to an integer:

    Int (your_data) convert to float: Float (your_data)

If this is not a dictionary, you need to convert it to a dictionary or json via:

json.loads (return object)

In your case, you can do:

    variable = client.get_spot_price()
    print type(variable) #if it is dictionary or not
    print float(variable["amount"]) #will return your price in float
0
source

Source: https://habr.com/ru/post/1615507/


All Articles