0

how to convert json to csv in python. want it open in excel with the lat and long columns.

[
  {
    "Lat": "-122.37391463199998",
    "Long": "47.630880207000075"
  },
  {
    "Lat": "-122.38447021399998",
    "Long": "47.70118823100006"
  },
  {
    "Lat": "-122.34729431799997",
    "Long": "47.64717111900006"
  }
]
edmamerto
  • 7,605
  • 11
  • 42
  • 66
  • 1
    Have you tried anything? – Alex Hall Mar 30 '17 at 20:57
  • 2
    Possible duplicate of [How can I convert JSON to CSV?](http://stackoverflow.com/questions/1871524/how-can-i-convert-json-to-csv) – 657784512 Mar 30 '17 at 20:58
  • Please show the relevant code and state the exact problem or error. A description alone is not enough. Also see [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – jww Dec 14 '19 at 18:46

2 Answers2

-1

You can use the json module to convert your string into a dictionary. Then use the csv module to save them into a file.

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)
fedeisas
  • 1,991
  • 2
  • 22
  • 34
-1

The csv module has a handy writerows() method on the DictWriter class:

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)
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135