Created
August 14, 2013 10:27
-
-
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.
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
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