-1

I have a CSV with the first row as the headers:

location_id name latitude longitude

I have then 10k rows of data. Latitude and Longitude are numbers

I need my output to look like that:

[
  {
    "location_id":"foo",
    "name":"bar",
    "latitude":28.55323,
    "longitude":-81.28482,
    "geo":{
        "__type": "GeoPoint",
        "latitude": 28.55323,
        "longitude": -81.28482
    }
  },
....
]

How can I do that in Python by writing a script? I'm using Python for Windows

admdrew
  • 3,790
  • 4
  • 27
  • 39
Stephane Maarek
  • 5,202
  • 9
  • 46
  • 87
  • What does your current code look like? Are you using the [`json` module](https://docs.python.org/3.4/library/json.html)? – admdrew Oct 28 '14 at 15:49
  • I'm trying to use this: http://stackoverflow.com/questions/19697846/python-csv-to-json But I can't get it to work, especially with the "geo" – Stephane Maarek Oct 28 '14 at 15:51
  • Can update your question with what *exactly* isn't working? – admdrew Oct 28 '14 at 15:53
  • 1
    Try next time to bring some effort in your question. Don't just ask how can I do that without any own approaches. – wenzul Oct 28 '14 at 16:07

3 Answers3

2

Based on my understanding, this seems to be what you want...
Warning: Untested code....

import csv, json

li = []
with open('myfile.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=' ')
    for location_id, name, latitude, longitude in reader:
        li.append({
           "location_id": location_id,
           "name": name,
           "latitude": latitude,
           "longitude": longitude,
           "geo": {
                "__type": "GeoPoint",
                "latitude": latitude,
                "longitude": longitude,
            }
        })
with open("outfile.geo", "w") as f:
    json.dump(li, f)
pradyunsg
  • 18,287
  • 11
  • 43
  • 96
1

I would use geojson. This is the format which you are dealing with.

>>> import geojson
>>> p = geojson.Point([0.0, 0.0])
>>> p
Point(coordinates=[0.0, 0.0])
>>> data = geojson.dumps(p)
'{"type": "Point", "coordinates": [0.0, 0.0]}'

Because you have no own approach yet this should be enough to generate some effort at your side.

wenzul
  • 3,948
  • 2
  • 21
  • 33
1

Thanks @SchoolBoy for his guidance

Final code:

import csv
import json

li = []
with open('test.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:


        li.append({
           "location_id": row["location_id"],
           "name": row["name"],
           "latitude": float(row["latitude"]),
           "longitude": float(row["longitude"]),
           "geo": {
                "__type": "GeoPoint",
                "latitude": float(row["latitude"]),
                "longitude": float(row["longitude"]),
            }
        })

json.dump(li,open('file.json','w'),indent=4,sort_keys=False)
Stephane Maarek
  • 5,202
  • 9
  • 46
  • 87