如何将json字典列表解析为cs

2024-06-25 22:40:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个从googleplacesapi检索到的json对象。该对象是一个包含三个键{'status'、'htmlattributions'、'results'}的字典。关键结果包含一个字典列表,其中包含我需要的信息,即“geography”dict中的纬度和经度。我需要将经度解析为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对象的实际外观如下:

^{pr2}$

Tags: csv对象json列表字典responsestatusresult
2条回答

所以我有另一种方法来解决这个问题。代码如下:

##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)

这似乎有效:

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文件的内容:

^{pr2}$

相关问题 更多 >