-3

I'm working on doing a live currency converter in Python. I've successfully fetched all the data needed from the URL into Python. However I'm now trying to call a specific string in the url. Here's my current code:

import urllib.request
import json

##Define JSON API Url
with urllib.request.urlopen("http://openexchangerates.org/api/latest.json?app_id=XXX") as url:
    response = url.read()

##Print Fetched data
print (response)

As you can see I've printed all the data it's fetched, but it's now printing specific strings from it.

My question is, how do i parse specific strings from the url ? I've heard of json.load ,is that something i should use ?

Stewartps
  • 45
  • 2
  • 9
  • 2
    what's the question? did you try `json.loads(response)`? – Jason Hu Mar 09 '15 at 20:22
  • Sorry my question has been edited. Could you explain further with the json.loads ? Thank you for the fast reply – Stewartps Mar 09 '15 at 20:23
  • better to search documentation first: https://docs.python.org/3/library/json.html – Jason Hu Mar 09 '15 at 20:25
  • Your question would have started out better had you just tried `json.loads()` *first*. You may have run into problems, but you could then at least have included the error message here. – Martijn Pieters Mar 09 '15 at 20:31

1 Answers1

1

You'll need to load the data as JSON; the json module can do this for you, but you need to decode the data to text first.

import urllib.request
import json

with urllib.request.urlopen("http://openexchangerates.org/api/latest.json?app_id=XXX") as url:
    response = url.read()

charset = url.info(). get_content_charset('utf-8')  # UTF-8 is the JSON default
data = json.loads(response.decode(charset))

From there on out data is a Python object.

Judging by the documenation you should be able to access rates as:

print('Euro rate', data['rates']['EUR'])

for example.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343