-2

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 ?

4
  • 2
    what's the question? did you try json.loads(response)? Commented Mar 9, 2015 at 20:22
  • Sorry my question has been edited. Could you explain further with the json.loads ? Thank you for the fast reply Commented Mar 9, 2015 at 20:23
  • better to search documentation first: docs.python.org/3/library/json.html Commented Mar 9, 2015 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. Commented Mar 9, 2015 at 20:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.