如何在python中将json转换为csv。希望它使用lat和long列在excel中打开。
[
{
"Lat": "-122.37391463199998",
"Long": "47.630880207000075"
},
{
"Lat": "-122.38447021399998",
"Long": "47.70118823100006"
},
{
"Lat": "-122.34729431799997",
"Long": "47.64717111900006"
}
]
答案 0 :(得分:0)
您可以使用json
模块将字符串转换为字典。然后使用csv
模块将它们保存到文件中。
import json, csv
json_string = '[{"Lat": "-122.37391463199998", "Long": "47.630880207000075"}, {"Lat": "-122.38447021399998", "Long": "47.70118823100006"}, {"Lat": "-122.34729431799997", "Long": "47.64717111900006"} ]'
data = json.loads(json_string)
with open('foo.csv', 'wb') as csvfile:
csv_writer = csv.DictWriter(csvfile, delimiter=',', fieldnames=['Lat', 'Long'])
csv_writer.writeheader()
csv_writer.writerows(data)
答案 1 :(得分:0)
csv
模块在writerows()
类上有一个方便的DictWriter
方法:
import csv
import json
data = json.loads(""" My Json """)
with open('lat_long.csv', 'w') as csvfile:
fieldnames = ['Lat', 'Long']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)