PythonからJSONを読み込もうとしています。ここに私のJSONオブジェクトがジオコード要求から返されます。PythonからJSONオブジェクトを読み取ると、タイプエラーが発生する
{
"results" : [
{
"address_components" : [
{
"long_name" : "Race Course Lane",
"short_name" : "Race Course Ln",
"types" : [ "route" ]
},
{
"long_name" : "Little India",
"short_name" : "Little India",
"types" : [ "neighborhood", "political" ]
},
{
"long_name" : "Singapore",
"short_name" : "Singapore",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Singapore",
"short_name" : "SG",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Race Course Ln, Singapore",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 1.3103311,
"lng" : 103.85354
},
"southwest" : {
"lat" : 1.3091323,
"lng" : 103.8523656
}
},
"location" : {
"lat" : 1.3097033,
"lng" : 103.8529918
},
"location_type" : "GEOMETRIC_CENTER",
"viewport" : {
"northeast" : {
"lat" : 1.311080680291502,
"lng" : 103.8543017802915
},
"southwest" : {
"lat" : 1.308382719708498,
"lng" : 103.8516038197085
}
}
},
"place_id" : "ChIJe5XzBMcZ2jERclOJt-xVp_o",
"types" : [ "route" ]
}
],
"status" : "OK"
}
私はジオメトリの下formatted_addressと緯度LNGを取得しようとしています。ここに私のコードは次のとおりです。
json_data = requests.get(url).json()
formatted_address = json_data['results'][0]['formatted_address']
print(formatted_address)
for each in json_data['results'][0]['geometry']:
print(each['lat'])
私はフォーマットされたアドレスをプリントアウトするために管理が、私はこのエラーメッセージ取得しています:
Traceback (most recent call last):
File "D:\Desktop\test.py", line 16, in <module>
print(each['lat'])
はTypeError例外:文字列のインデックスは整数
任意のアイデアでなければなりませんの?ありがとう!
'for x in d ['results'] [0] ['geometry']'結果はキーの繰り返しになります。 –
そして、キーは文字列なので、 'str [str]'はエラーになります。おそらくあなたが望むだろう: 'x = json_data ['results'] [0] ['geometry']; for each in x:x [each] ['lat'] ' –
これは、すべてのキーと値のペアがlatキーでdictを持つわけではないので、別のエラーになります。 JSONをもう一度見て、座標フォームを抽出したいところを見つけてください。 「場所」? –