如何将字典的json列表解析为csv [英] How to parse a json list of dictionaries to csv

查看:72
本文介绍了如何将字典的json列表解析为csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从Google Places API中检索到的json对象.该对象是具有三个键{'status','html_attributions','results'}的字典.关键结果包含一个词典列表,其中包含我需要的信息,即地理位置"字典中的纬度,经度.我需要将经度解析为csv文件,以供以后处理.到目前为止,这是我拥有的代码:

I have a json object retrieved from the google places api. The object is a dictionary with three keys {'status', 'html_attributions', 'results'}. The key results contain a list of dictionaries with the information that I need which is the latitude, longitude inside the 'geography' dict. I need to parse the lat longitude to a csv file for later processing. So far this is the code that I have:

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)

这将写出纬度和经度(虽然不是很干净,但是可以完成工作).但是,我需要对列表中的所有元素执行此操作.有关如何执行此操作的任何建议?

This writes the latitude and longitude (not perfectly clean but it does the job). However I need to do this for all the elements in the list. Any suggestions on how to do this?

这是json对象的实际外观:

This is how the json object actually looks like:

*{'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'}*

推荐答案

这似乎可行:

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

这篇关于如何将字典的json列表解析为csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆