我对此的困难比我应该的更多!
我试图从下面的bing地图JSON中提取postalCode:
{
"authenticationResultCode":"ValidCredentials",
"brandLogoUri":"http:\/\/dev.virtualearth.net\/Branding\/logo_powered_by.png",
"copyright":"Copyright © 2014 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
"resourceSets":[
{
"estimatedTotal":1,
"resources":[
{
"__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",
"bbox":[
56.216052482429326,
-2.9494141659354827,
56.223777917570679,
-2.9308900340645176
],
"name":"Street, Leven, KY8 5",
"point":{
"type":"Point",
"coordinates":[
56.2199152,
-2.9401521
]
},
"address":{
"addressLine":"Street",
"adminDistrict":"Scotland",
"adminDistrict2":"Fife",
"countryRegion":"United Kingdom",
"formattedAddress":"Street, Leven, KY8 5",
"locality":"Leven",
"postalCode":"KY8 5"
},
"confidence":"Medium",
"entityType":"Address",
"geocodePoints":[
{
"type":"Point",
"coordinates":[
56.2199152,
-2.9401521
],
"calculationMethod":"Interpolation",
"usageTypes":[
"Display",
"Route"
]
}
],
"matchCodes":[
"Good"
]
}
]
}
],
"statusCode":200,
"statusDescription":"OK",
"traceId":"8fdd75362a694e02a45fa17d6e7c0e95|DB40080932|02.00.108.1000|DB4SCH010061257, DB4SCH010061346"
}
我的代码只返回字段名称而不是属性:
r = requests.get(current_url)
json_data = r.json()
for item in json_data['resourceSets'][0]['resources']:
for field in item['address']:
print field
我错过了什么?对不起,新手问题!
答案 0 :(得分:2)
for field in item['address']
默认只遍历item['address']
(字典)中的密钥,因此您需要:
for item in json_data['resourceSets'][0]['resources']:
for field in item['address']:
print field, item['address'][field]
答案 1 :(得分:1)
对于Python中的字典循环,只需遍历键即可。如果您也想要这些值,则应使用.items()
:
for field, value in item['address'].items():
print field, value