我有一个从simplejson.load()函数返回的数据字典(?)。它看起来像这样......
{'status': 'OK', 'results': [{'geometry': {'location_type': 'APPROXIMATE', 'bounds': {'northeast': {'lat': 53.86121, 'lng': -2.045072}, 'southwest': {'lat': 53.80570600000001, 'lng': -2.162588}}, 'viewport': {'northeast': {'lat': 53.8697753, 'lng': -2.0725853}, 'southwest': {'lat': 53.81711019999999, 'lng': -2.2006447}}, 'location': {'lat': 53.84345099999999, 'lng': -2.136615}}, 'address_components': [{'long_name': 'Trawden', 'types': ['sublocality', 'political'], 'short_name': 'Trawden'}, {'long_name': 'Colne', 'types': ['locality', 'political'], 'short_name': 'Colne'}, {'long_name': 'Lancashire', 'types': ['administrative_area_level_2', 'political'], 'short_name': 'Lancs'}, {'long_name': 'United Kingdom', 'types': ['country', 'political'], 'short_name': 'GB'}], 'formatted_address': 'Trawden, Colne, Lancashire, UK', 'types': ['sublocality', 'political']}]}
我如何获得例如结果 - > geometry-> location-> lat?
这个结构是普通的python字典吗?
编辑:请有人也解释一下simplejson.dumps()函数。我发现这些文档并不具有启发性。感谢
非OP编辑:这是JSON,非常印刷:
{
"status":"OK",
"results":[
{
"geometry":{
"location":{
"lat":53.843450999999988,
"lng":-2.1366149999999999
},
"location_type":"APPROXIMATE",
"viewport":{
"northeast":{
"lat":53.869775300000001,
"lng":-2.0725853000000001
},
"southwest":{
"lat":53.817110199999988,
"lng":-2.2006446999999998
}
},
"bounds":{
"northeast":{
"lat":53.86121,
"lng":-2.0450719999999998
},
"southwest":{
"lat":53.805706000000008,
"lng":-2.162588
}
}
},
"address_components":[
{
"long_name":"Trawden",
"short_name":"Trawden",
"types":[
"sublocality",
"political"
]
},
{
"long_name":"Colne",
"short_name":"Colne",
"types":[
"locality",
"political"
]
},
{
"long_name":"Lancashire",
"short_name":"Lancs",
"types":[
"administrative_area_level_2",
"political"
]
},
{
"long_name":"United Kingdom",
"short_name":"GB",
"types":[
"country",
"political"
]
}
],
"formatted_address":"Trawden, Colne, Lancashire, UK",
"types":[
"sublocality",
"political"
]
}
]
}
答案 0 :(得分:4)
是的,确实如此。如果将它存储在名为d
的变量中,那么您将使用...
d['results'][0]['geometry']['location']
等等。请注意[0]
,因为带有键'geometry'
的字典在列表中。
simplejson.load()
将JSON对象映射到Python dict
,将JSON列表映射到list
。非常简单;不要过分思考它。
simplejson.dumps()
只是与simplejson.loads()
相反 - 它接受任何标准的Python对象,并将其转储到一个字符串,该字符串是该对象的JSON表示。例如:
>>> q = {}
>>> q['foo'] = 'bar'
>>> q[1] = 'baz'
>>> simplejson.dumps(q)
'{"1": "baz", "foo": "bar"}'