从Python读取JSON对象导致TypeError

问题描述 投票:-1回答:1

我试图从Python中读取JSON。这是我从地理编码请求返回的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"
}

我试图在geometry下获取formatted_address和lat 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:字符串索引必须是整数

有任何想法吗?谢谢!

python json
1个回答
2
投票

json_data['results'][0]['geometry']是一个_dict_。这意味着,for x in json_data['results'][0]['geometry']将导致对键的迭代,其中x是分配了键(字符串)的循环变量。这是一个例子 -

d = {'a' : 'b', 'c' : 'd'}

for each in d:
     print(x)   

a
c

由于each是一个字符串,each['lat']将是一个无效的操作(因为你不能用除整数之外的任何东西索引字符串)。


观察JSON文件的结构 -

{
    "location_type": "GEOMETRIC_CENTER",
    ...

    "location": {
        "lng": 103.8529918,
        "lat": 1.3097033
    }
}

仔细观察,只有location有与latlng键相关的词典。如果你想要的只是这些值,那么只需直接索引它们。不需要循环。

x = json_data['results'][0]['geometry']['location']
lat, lng = x['lat'], x['lng']
© www.soinside.com 2019 - 2024. All rights reserved.