如何将json的字典列表解析为csv

时间:2014-03-12 02:05:28

标签: python json google-places-api export-to-csv

我有一个从google places api检索到的json对象。该对象是一个包含三个键{'status','html_attributions','results'}的字典。关键结果包含一个字典列表,其中包含我需要的信息,即“地理”字典中的纬度,经度。我需要将lat经度解析为csv文件以供以后处理。到目前为止,这是我的代码:

response = urllib2.urlopen(url)
result = response.read()
d = simplejson.loads(result)
g=d['results']    
y=g[0]
y
z=dict.items(y['geometry'])
with open('test3.csv','w') as f:
    w = csv.writer(f)
    w.writerows(z)

这会写出纬度和经度(不完全干净,但它可以完成工作)。但是我需要对列表中的所有元素执行此操作。有关如何做到这一点的任何建议?

这就是json对象的实际外观:

*{'html_attributions': [u'Listings by <a href="http://www.gelbeseiten.de/">GelbeSeiten\xaeVerlagen</a>'],
 'results': [{'geometry': {'location': {'lat': 52.164737, 'lng': 9.964918}},
              'icon': 'http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png',
              'id': '6632006e0c9e43ca1436804cb00b7babf1ea3c2a',
              'name': "McDonald's",
              'opening_hours': {'open_now': True},
              'photos': [{'height': 608,
                          'html_attributions': ['<a href="https://plus.google.com/106802039558898860276">Tarek Tounsi</a>'],
                          'photo_reference': 'CnRpAAAAz35IbT8YWMJYJp7pBJs-IeDu7fI0_c9bUsYZui2rPn3rSjLFAO8JqbI28pd0sr5Q25KUideKfq1oAKT_T9LUlyTMpciCZCynzXEE6fNfQAvmLwc78gbG515PLor_8B82NUHIl49HsxkMmPhmnk3m8BIQsHFRud-4_w9fhnTdW6E3zRoU2oKQj3kWfPYDdZ45H9Q1mAwAuQA',
                          'width': 1024}],
              'price_level': 1,
              'rating': 3.8,
              'reference': 'CnRrAAAA9DxXNvv_eFpLX9MjhiTgvR6_0wrl4KROEu1fmoVexrFXaNH88r6IHPMUPTONbuuKlfZBXXJ4byaDKty5niJmW6StJLQkHrCX1tqXE9lubrJY4yw32vq5n0Z37X00ulGsFB7xJe2ADD_jtNDdim4v9hIQHRxmz9XRuZw4U4QqRtljrhoUoULu8xeuYgi7qMUNArThb0bCjhk',
              'types': ['restaurant', 'food', 'establishment'],
              'vicinity': u'Bavenstedter Stra\xdfe 48, Hildesheim'},
             {'geometry': {'location': {'lat': 52.380744, 'lng': 9.861758}},
              'icon': 'http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png',
              'id': '60317f570db420888a7fba543683db2450750c68',
              'name': "McDonald's Restaurant",
              'opening_hours': {'open_now': False},
              'price_level': 1,
              'reference': 'CoQBdwAAALC9DEmsiTdQ9rSuogeUprKt-UCTNo5Jmwi7l1iUevq_TjNyi19DWraSBuJxZ67lV9GGICahVl_gI8rYk20AmbX8-jzmDay0aQZGCJZgKCU2JFjgFW5enaqSA6twat1kXDoSetimJbxioI3JlFHr3Lvdb2w6mSOpst4GKzBwRMSEEhCi_nAkNmCo0AikA-7oW-8YGhQLSxUZek9wlngI8YUYpwSMk4AuMw',
              'types': ['restaurant', 'food', 'establishment'],
              'vicinity': u'Kreisstra\xdfe 2, Hanover'},
             {'geometry': {'location': {'lat': 52.412797, 'lng': 9.734524}},
              'icon': 'http://maps.gstatic.com/mapfiles/place_api/icons/restaurant71.png'}*

2 个答案:

答案 0 :(得分:1)

这似乎有效:

fields = 'lat', 'lng'
with open('test3.csv', 'wb') as csvfile:
    w = csv.writer(csvfile)
    w.writerow(fields)  # optional -- header row
    w.writerows(operator.itemgetter(*fields)(result['geometry']['location'])
                    for result in d['results'])

生成的test3.csv文件的内容:

lat,lng
52.164737,9.964918
52.380744,9.861758
52.412797,9.734524

答案 1 :(得分:0)

所以我有另一种解决方法。这是代码:

##remember that d is the dictionary that has the key 'results', which is also a list of dictionaries
g=d['results']
z=[d['geometry']['location'] for d in g]
keys=['lat','lng']

with open('C:/Users/J/Desktop/test4.csv', 'wb') as csvfile:
     dict_writer = csv.DictWriter(csvfile, keys)         
     dict_writer.writer.writerow(keys)         
     dict_writer.writerows(z)