Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am needing a Python script to convert CSV data to GeoJSON output. The output should match the format, below:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates":  [ -85.362709,40.466442 ]
      },
      "properties": {
        "weather":"Overcast",
        "temp":"30.2 F"
      }
    }
  ]
}

I am using this script to run the process, but it does not produce the desired output:

import csv, json
    li = []
    with open('CurrentObs.csv', newline='') as csvfile:
        reader = csv.reader(csvfile, delimiter=',')
        for latitude, longitude, weather, temp in reader:
            li.append({
               "latitude": latitude,
               "longitude": longitude,
               "weather": weather,
               "temp": temp,
               "geo": {
                    "__type": "GeoPoint",
                    "latitude": latitude,
                    "longitude": longitude,
                }
            })

    with open("GeoObs.json", "w") as f:
        json.dump(li, f)

Any help is greatly appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

one could use directly the geojson package:

import csv, json
from geojson import Feature, FeatureCollection, Point

features = []
with open('CurrentObs.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    for latitude, longitude, weather, temp in reader:
        latitude, longitude = map(float, (latitude, longitude))
        features.append(
            Feature(
                geometry = Point((longitude, latitude)),
                properties = {
                    'weather': weather,
                    'temp': temp
                }
            )
        )

collection = FeatureCollection(features)
with open("GeoObs.json", "w") as f:
    f.write('%s' % collection)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...