0

I am using Python for the first time to create a simple JSON parser. However, when printing the JSON data to the console, it includes many extra brackets and other symbols that are unwanted. I am also running Python 2.7.10.

import json
from urllib2 import urlopen

response = urlopen("https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json")
source = response.read()

# print(source)

data = json.loads(source)

# print(json.dumps(data, indent=2))

usd_rates = dict()

for item in data['list']['resources']:
    name = item['resource']['fields']['name']
    price = item['resource']['fields']['price']
    usd_rates[name] = price
    print(name, price)

And the output is as follows:

enter image description here

When I try to change the python version to 3.7.10:

enter image description here

JSON_Derulo
  • 892
  • 2
  • 14
  • 39

2 Answers2

2

I think you are actually printing a tuple with python 2 print syntax and the u character is a unicode flag (What exactly do "u" and "r" string flags do, and what are raw string literals?).

Also in python 3 you couldn't use urllib2 but would have to use urllib.request.

This code works for me (python 3.6.5):

import json
from urllib.request import urlopen

response = urlopen("https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json")
source = response.read()


data = json.loads(source)

usd_rates = dict()

for item in data['list']['resources']:
    name = item['resource']['fields']['name']
    price = item['resource']['fields']['price']
    usd_rates[name] = price
    print(name, price)

EDIT ---------

From the image you posted it looks like you have python 3 installed but your usr/bin/python is a symbolic link to usr/bin/python2.

If you want to run python 3 by default you could create an alias. Check this link for more info https://askubuntu.com/questions/320996/how-to-make-python-program-command-execute-python-3 (should be valid info for macs too)

cornacchia
  • 473
  • 2
  • 9
  • See the image above for what happens when I try to change the python version – JSON_Derulo Jul 04 '18 at 11:05
  • From the image you posted it looks to me that you have opened the python3 console. If you want to run a script from shell you could type something like `python3 script.py` – cornacchia Jul 04 '18 at 12:16
-2

Convert name and price to string

print(str(name), str(price))

or use

name = str(item['resource']['fields']['name'])

Sreekanth
  • 87
  • 2
  • 8