Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.