我正在尝试从API库中获取特定数据:
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']
当脚本启动时,我得到:
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
如果从['name']
中删除item['name']
,则脚本可以正常运行并打印出数据。为什么以及如何使其发挥作用?对于不同的API,我有完全相同的脚本,工作正常。
P.S。:我正在寻找的数据是:
{"_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"}
答案 0 :(得分:1)
company
是单个词典,而不是列表。所以你不需要迭代它:只做print data['company']['name']
。