Friday, 4 September 2015

leaflet - Is it possible to convert regular JSON to GeoJSON?


My apologies if this is a repeat question, I searched here and couldn't find an answer. I have JSON data I've exported from Openpaths.cc which contains lat and lon values. However, the data is not in GeoJSON format so can't be read by OGR2OGR. Could anyone point me in the right direction on how to convert my data to GeoJSON? I'd ultimately like to display it with Leaflet. Here is what the data looks like:


[
{
"lon": -73.97,

"device": "iPhone3,3",
"version": "1.1",
"t": 1381167616,
"lat": 40.66,
"alt": 67,
"os": "6.1.3"
},
{
"lon": -73.96,
"device": "iPhone3,3",

"version": "1.1",
"t": 1381171200,
"lat": 40.66,
"alt": 45,
"os": "6.1.3"
}

]



Answer



So this python script will take a json input file as detailed above and write properly formatted geojson to the output file.



run the script in terminal by doing python scriptname.py input_file.json output_file.json


#! usr/bin/env python

from sys import argv
from os.path import exists
import simplejson as json

script, in_file, out_file = argv

data = json.load(open(in_file))


geojson = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry" : {
"type": "Point",
"coordinates": [d["lon"], d["lat"]],
},

"properties" : d,
} for d in data]
}


output = open(out_file, 'w')
json.dump(geojson, output)

print geojson

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...