4

I am trying to work with Coinbase's 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 the 316.08. How can I solve it?

Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
ctrigose
  • 51
  • 3

3 Answers3

1
data = {
  "amount": "316.08", 
  "currency": "USD"
}
price = float(text['amount'])

With API use JSON parser

import json
data = client.get_spot_price()
price = float(json.loads(data)['amount'])
print price
Harwee
  • 1,601
  • 2
  • 21
  • 35
  • Thanks the first method works, even when I call 'price = float(text['amount'])' with price being the API object it works great. – ctrigose Nov 12 '15 at 01:23
  • First method works here because API response here is very simple with only two values. Where as for example twitter has more data in it's API response and its easy to gather data after parsing with JSON. – Harwee Nov 12 '15 at 01:27
0

It looks like a json output. You could import json library in python and read it using the loads method, for sample:

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)
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
0

At first you put your returned object into a variable and check the type of the returned value. just like this:

print type(your_returned object/variable)

If this is dictionary You can access data from a dictionary via dictionary key. A dictionary structure is:

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

1.You can access all values of dictionary. like below:

print dict[key_1] #output will be returned value_1

  1. Then you can convert returned data to integer or float. For converting to integer:

    int(your_data) convert to float: float(your_data)

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

json.loads(your returned 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
MA Saleh
  • 1
  • 2