简体   繁体   中英

TypeError: string indices must be integers while fetching data from API

I am trying to get particular data from API's library:

import urllib2
import json
import csv

c = csv.writer(open("analysis output.csv", "wb"))

urlIncomeStatement = 'http://dev.c0l.in:5984/income_statements/_all_docs'
apiIncomeStatement = urllib2.urlopen(urlIncomeStatement)
dataIncomeStatement = json.load(apiIncomeStatement)

urlFinancialPosition = 'http://dev.c0l.in:5984/financial_positions/'
apiFinancialPosition = urllib2.urlopen(urlFinancialPosition)
dataFinancialPosition = json.load(apiFinancialPosition)


for item in dataIncomeStatement['rows']:
    url = 'http://dev.c0l.in:5984/income_statements/' + item['id']
    api = urllib2.urlopen(url)
    data = json.load(api)
    for item in data['company']:
        print item['name']

When script is launched, in the end I get:

Traceback (most recent call last):
  File "C:\Users\gnite_000\Documents\BIT course 1\github\1415-bit-project2-parveen-group-01\extendedAPI.py", line 21, in <module>
    print item['name']
TypeError: string indices must be integers

If ['name'] is removed from item['name'] , then script works fine and it print out the data. Why and how do I make it work? I have exactly same script for different API which is working fine.

PS: The data I am looking for is:

{"_id":"30e901a7b7d8e98328dcd77c3600fa43","_rev":"1-689f7618387b071a0107a69fe24e410d","id":26,"sector":"services","company":{"name":"Abatz","non_current_assets":1300369.5,"current_assets":1323444.5900000000838,"equity":867440.68000000005122,"non_current_liabilities":376096.35999999998603,"current_liabilities":512456.94000000000233},"date":"2012-10-31"}

company is a single dict, not a list. So you don't need to iterate through it: just do print data['company']['name'] .

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