Last active
April 11, 2018 19:52
-
-
Save bertspaan/6229814 to your computer and use it in GitHub Desktop.
Ruby script to split GeoJSON file(s) into separate files, one for each feature.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: UTF-8 | |
require 'json' | |
require 'fileutils' | |
ARGV.select{ |file| [".json", ".geojson"].include? File.extname(file) }.each do |file| | |
basename = File.basename(file, File.extname(file)) | |
geojson = JSON.parse(File.open(file).read) | |
if geojson.has_key? "features" | |
# Create directory if not exists: | |
unless Dir.exists?(basename) | |
Dir.mkdir(basename) | |
end | |
geojson["features"].each_with_index { |feature, index| | |
single_geojson = { | |
"type" => "FeatureCollection", | |
"features" => [feature] | |
} | |
l = geojson["features"].length.to_s.length | |
n = "%0#{l}d" % index | |
single_file = "#{basename}/#{basename}_#{n}.geojson" | |
puts "Writing file #{index + 1}/#{geojson["features"].length}: #{single_file}" | |
File.open(single_file, 'w') { |file| file.write(JSON.pretty_generate(single_geojson)) } | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment