JSON to Shapefile

31 Jan

Toronto has a bunch of open data – which is awesome! Someone I follow on Twitter was looking to convert some parking JSON to a Shapefile. I haven’t used it much, but python has a JSON module in 2.7 and SimpleJSON in 2.5. And of course, writing shapefiles is simple with shapefile.py.

JSON is a dictionary. Once it is loaded in a data variable, you can call items by the key. So for the carparks, I could call: data[“carparks”][i][“id”] or data[“carparks”][i][“lat”], where i is the index or the array. Then iterate, while i < len(data[“carparks”]).

Here is the full code:

import shapefile
import json

json_data=open(‘greenPParking.json’)
data = json.load(json_data)

w=shapefile.Writer(shapefile.POINT)
w.field(“id”)
w.field(“address”)
w.field(“lat”)
w.field(“lng”)
w.field(“rate”)
w.field(“rate_half_hour”)
w.field(“carpark_type”)
w.field(“carpark_type_str”)
w.field(“capacity”)
w.field(“max_height”)
w.field(“payment_options”)

i=0 # should be changed to — while (i < len(data[“carparks”]))
while (i<243):

w.point(float(data[“carparks”][i][“lng”]),float(data[“carparks”][i][“lat”]))
w.record(data[“carparks”][i][“id”],data[“carparks”][i][“address”],data[“carparks”][i][“lat”],data[“carparks”][i][“lng”],data[“carparks”][i][“rate”],data[“carparks”][i][“rate_half_hour”],data[“carparks”][i][“carpark_type”],data[“carparks”][i][“carpark_type_str”],data[“carparks”][i][“max_height”],data[“carparks”][i][“capacity”],data[“carparks”][i][“payment_options”],data[“carparks”][i][“rate_details”])
i+=1

prj = open(“csvSHP.prj”, “w”)
epsg = ‘GEOGCS[“WGS 84”,’
epsg += ‘DATUM[“WGS_1984”,’
epsg += ‘SPHEROID[“WGS 84”,6378137,298.257223563]]’
epsg += ‘,PRIMEM[“Greenwich”,0],’
epsg += ‘UNIT[“degree”,0.0174532925199433]]’
prj.write(epsg)
prj.close()

w.save(“greenPParkingSHP”)
json_data.close()

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: