Reputation: 23
I am very new to programming and I am having a problem with the following:
I have a very simple and perhaps pointless task whereby I am trying to take longitude and latitude data from a JSON API and write to a CSV file. I have based the code on another that seems to work OK.
I keep getting the following error code:
c.writerow([item['latitude']])_TypeError: string indices must be integers
Can anyone help me??
JSON code from http://api.open-notify.org/iss-now.json
{
"iss_position": {
"latitude": 17.03894678089794,
"longitude": 1.17550020887323
},
"message": "success",
"timestamp": 1463137065
}
My Python Code
import requests
import csv
r = requests.get("http://api.open-notify.org/iss-now.json").json()
c = csv.writer(open("ISS.csv", "w"),lineterminator='\n')
for item in r['iss_position']:
c.writerow([item['latitude'],['longitude']])
Error Message
C:\Python35\python.exe C:/Users/Ian/PycharmProjects/ISS/ISS.py
Traceback (most recent call last):
File "C:/Users/Ian/PycharmProjects/ISS/ISS.py", line 10, in <module>
c.writerow([item['latitude']])
TypeError: string indices must be integers
Process finished with exit code 1
Upvotes: 0
Views: 1902
Reputation: 1650
The value assigned to iss_position
key (r['iss_position']
) is a dictionary. So, iterating over it will yield keys (strings) rather than values (coordinates). It seems that this will do in this case:
c.writerow([r['iss_position']['latitude'],r['iss_position']['longitude']])
The for
loop is not needed anymore. There are two keys in the dictionary under 'iss_position'
key, so the loop turned twice. It's enough to call the code above once.
Upvotes: 2