从Python读取JSON对象导致TypeError

时间:2017-12-16 14:01:13

标签: python json

我正在尝试从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:字符串索引必须是整数

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:2)

list: 5, 4, 3, 2, 1, CustomSequence: x4, x3, x2, x1, x0, FunkyBackwards: B, A, C, K, W, A, R, D, S, !, 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将是一个无效的操作(因为你不能用除整数之外的任何东西索引字符串)。

观察JSON文件的结构 -

each['lat']

仔细观察,只有{ "location_type": "GEOMETRIC_CENTER", ... "location": { "lng": 103.8529918, "lat": 1.3097033 } } 有一个与locationlat相关联的词典。如果你想要的只是这些值,那么只需直接索引它们。不需要循环。

lng