Skip to content

Instantly share code, notes, and snippets.

@bertspaan
Created August 14, 2013 10:27
Show Gist options
  • Save bertspaan/6229816 to your computer and use it in GitHub Desktop.
Save bertspaan/6229816 to your computer and use it in GitHub Desktop.
Ruby script to split GeoJSON file(s) into separate files, one for each feature.
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]
}
single_file = "#{basename}/#{basename}_#{index}.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