Skip to content

Instantly share code, notes, and snippets.

@bertspaan
Last active April 11, 2018 19:52
Show Gist options
  • Save bertspaan/6229814 to your computer and use it in GitHub Desktop.
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.
# 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