简体   繁体   中英

Returning specific value from imported JSON

This is my first time retrieving JSON information from a webpage. My goal is to show the current gold price, which I'd like to retrieve from a free source.

The current code is working:

    import urllib.request
    import json

request = urllib.request.urlopen("https://forex-data-feed.swissquote.com/public-quotes/bboquotes/instrument/XAU/USD")
data = json.load(request)
print(data[0])

I expected this imported data to be a dict type, but it is a list somehow?

The print:

{'topo': {'platform': 'MT5', 'server': 'Live1'}, 'spreadProfilePrices': [{'spreadProfile': 'Standard', 'bidSpread': 14, 'askSpread': 14.1, 'bid': 1921.59, 'ask': 1921.9}, {'spreadProfile': 'Premium', 'bidSpread': 12.7, 'askSpread': 12.7, 'bid': 1921.59, 'ask': 1921.9}, {'spreadProfile': 'Prime', 'bidSpread': 11.3, 'askSpread': 11.3, 'bid': 1921.59, 'ask': 1921.9}], 'ts': 1598379583052}

Now I'm trying to receive the value stored in spreadProfile Standard -> 'ask'.

This is probably a rookie question but I'm not getting why I'm unsuccesful. Could anyone provide me help with this and especially on how did you come up with the solution?

The print is not a list, but a dict. The webpage is returning a list of dicts and by doing data[0] , you're selecting the first dict in the list. (Are you sure you want to select the first one?)

In order to get ask, you would first you need to find the Standard profile. I do that here by looping through all the profiles and testing, if the one that is looped through is Standad. If the one we're looping through is in fact Standard, then just select 'ask' and break out of the loop.

for profile in data[0]['spreadProfilePrices']:
     if profile['spreadProfile'] == 'Standard':
          print(profile['spreadProfile']['ask'])
          break

You should read more on what how lists and dictionaries work in Python :) Here are some resources I'd personally recommend:

Python lists: https://www.w3schools.com/python/python_lists.asp

Python dicts: https://www.w3schools.com/python/python_dictionaries.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM