简体   繁体   中英

TypeError: string indices must be integers when trying to extract data from an API using Python

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

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.

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