I have some JSON that I want to loop over (simplified):
{
"Meta Data": {
"1. Information": "Daily Prices (open, high, low, close) and Volumes",
"2. Symbol": "TGT",
"3. Last Refreshed": "2018-11-20 14:50:52",
"4. Output Size": "Compact",
"5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
"2018-11-20": {
"1. open": "67.9900",
"2. high": "71.5000",
"3. low": "66.1500",
"4. close": "69.6800",
"5. volume": "15573611"
},
"2018-11-19": {
"1. open": "79.9300",
"2. high": "80.4000",
"3. low": "77.5607",
"4. close": "77.7900",
"5. volume": "9126929"
}
}
The dates are values that I do not know beforehand and change every day, so I want to loop over them and print the date with the open, high, low, etc. So far all I have been able to do is loop over the dates and print them, but when I tried to get the other values, being new to JSON reading, I failed with the following code:
import urllib.parse
import requests
code = 'TGT'
main_api = ('https://www.alphavantage.co/query? function=TIME_SERIES_DAILY&symbol=' +
code + '&apikey=RYFJGY3O92BUEVW4')
url = main_api + urllib.parse.urlencode({'NYSE': code})
json_data = requests.get(url).json()
#print(json_data)
for item in json_data['Time Series (Daily)']:
print(item)
for item in json_data[item]:
print(item)
I also tried doing:
for v in json_data:
print(v['1. open'])
Instead of nesting, but it nevertheless did not work. On both tries, I get the same error:
Traceback (most recent call last):
File "jsonreader.py", line 26, in <module>
for item in item['Time Series (Daily)'][item]:
TypeError: string indices must be integers
So anyone know how to loop through all the dates and get out the open, high, low, etc from them?
The full version of the JSON is available here.