-2

I have an API call result in Python which is returning the following:

b'[{"type":"deposit","currency":"bch","amount":"0.00000001","available":"0.00000001"}]'

I tried to extract the value 0.00000001 but without any success. I know how to extract values from lists and dictionaries in Python,but as there is the b' value before the results I am not figuring out how to get it.

Any ideas?

Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
Nanor
  • 21
  • 3
  • Possible duplicate of [Parsing HTTP Response in Python](https://stackoverflow.com/questions/23049767/parsing-http-response-in-python) – Aran-Fey Feb 21 '18 at 11:59
  • Possible duplicate of [Convert dictionary to bytes and back again python?](https://stackoverflow.com/questions/19232011/convert-dictionary-to-bytes-and-back-again-python) – Georgy Feb 21 '18 at 12:10

2 Answers2

4

I think what you have here is actually a bytes string, rather than a Python dictionary. Try this to convert it to a dictionary (actually a list containing a dictionary given the square brackets):

import json
data = json.loads(b'[{"type":"deposit","currency":"bch","amount":"0.00000001","available":"0.00000001"}]')
value = data[0]['amount']
sjw
  • 6,213
  • 2
  • 24
  • 39
  • it works under python2 but I am using python3, current error when executing your lines is TypeError: the JSON object must be str, not 'bytes' – Nanor Feb 21 '18 at 20:30
  • I just tested on Python 3 and it works correctly for me. To be exact, Python 3.6.1, and json module version 2.0.9. – sjw Feb 21 '18 at 22:23
  • Problem solved, that was it, under 3.5 it was not working, updated to 3.6.1 and problem got solved. Thanks – Nanor Feb 22 '18 at 09:04
0

The API is probably returning json data, you should parse it this way:

import json
data = json.loads(json_data)
print data[0]['amount']

json_data is what the API returns

Vyko
  • 212
  • 1
  • 6