Skip to content

Instantly share code, notes, and snippets.

@WindfallLabs
Created August 7, 2017 21:08
Show Gist options
  • Save WindfallLabs/f3995386aa4ef3443e28f1e5cdcd6864 to your computer and use it in GitHub Desktop.
Save WindfallLabs/f3995386aa4ef3443e28f1e5cdcd6864 to your computer and use it in GitHub Desktop.
Makes a geojson-dashboard config.json file from an input geojson file.
# -*- coding: utf-8 -*-
"""
Makes a geojson-dashboard config.json file from an input geojson file.
Author: Garin Wally; Aug 2017
Use:
> python make_config.py us_bounds.json
"""
import os
import sys
import json
from collections import OrderedDict
config = """
var config = {
geojson: "<file.geojson>",
title: "<App Title>",
layerName: "<layer name>",
hoverProperty: "<hover fieldname>",
sortProperty: "<inital sorting field>",
sortOrder: "desc"
};
""".strip()
prop_template = """{
value: "{field_name}",
label: "{field_name}",
table: {
visible: true,
sortable: true
},
filter: {
type: "{data_type}"//,
//input: "checkbox",
//vertical: true,
//multiple: true,
//operators: ["in", "not_in", "equal", "not_equal"],
//values: []
},
info: true}"""
types = {
"int": "integer",
"float": "float", # TODO: or real
}
def map_str_type(s):
if s is None:
return "string"
elif type(s) in [str, unicode]:
if s.startswith("0") and s.isdigit():
return "string"
elif s.isdigit():
return "integer"
elif s.replace(".", "").isdigit():
return "float" # TODO: or real?
else:
return "string"
else:
try:
return types[type(s).__name__]
except:
return "string"
def get_json_fields(json_file):
with open(json_file, "r") as f:
json_content = json.load(f)
feature1 = json_content["features"][0]
fields = OrderedDict()
for k, v in feature1["properties"].items():
fields[k] = map_str_type(v)
return fields.items()
def make_config(geojson):
"""Makes a geojson-dashboard config file."""
dlist = []
for fname, dtype in get_json_fields(geojson):
dlist.append(
prop_template.replace("{field_name}", fname
).replace("{data_type}", dtype))
prop = "var properties = [" + ",\n\n".join(dlist) + "\n];"
with open("config.json", "w") as f:
f.write(config)
f.write("\n\n")
f.write(prop)
return
def main():
if len(sys.argv) > 1:
geojson = sys.argv[1]
else:
geojson = raw_input("Enter geojson filepath: ")
if os.path.exists(geojson):
try:
make_config(geojson)
print("Complete.\n")
except Exception as e:
print(e)
else:
print("Failed: Input does not exist.\n")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment