解析数据JSON和Python

解析数据JSON和Python

问题描述:

import requests 

url = "http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo" 
request = requests.get(url) 
fetch_data = request.json() 

print (request.content) 

for item in fetch_data: 
    print(item) 

我试图在JSON请求geonames -> lng内获取项目。如果我利用item['lng']解析数据JSON和Python

然后得到错误JSON请求

{ 
    "geonames":[ 
     { 
     "lng":-99.12766456604, 
     "geonameId":3530597, 
     "countrycode":"MX", 
     "name":"Mexiko-Stadt", 
     "fclName":"city, village,...", 
     "toponymName":"Mexico City", 
     "fcodeName":"capital of a political entity", 
     "wikipedia":"en.wikipedia.org/wiki/Mexico_City", 
     "lat":19.428472427036, 
     "fcl":"P", 
     "population":12294193, 
     "fcode":"PPLC" 
     } 
    ] 
} 
+0

你遍历*字典*'fetch_data',所以'item'是关键(例如''geonames''),这是一个字符串,如错误消息告诉您。 – jonrsharpe

+0

在fetch_data.enumerate()中使用''key,item:' – Barmar

+1

@Barmar''dict'对象没有属性'enumerate'' ...? –

尝试

TypeError: string indices must be integers 

例子;

for item in fetch_data['geonames']: 
    print(item['lng']) 
+0

谢谢!它效果很好 – Kris1511