Skip to content

Instantly share code, notes, and snippets.

@coorasse
Created November 17, 2021 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coorasse/f90c4badfdc36f42e4ebd23dfaac0fc4 to your computer and use it in GitHub Desktop.
Save coorasse/f90c4badfdc36f42e4ebd23dfaac0fc4 to your computer and use it in GitHub Desktop.
Dump large table to JSON file in ruby
File.open(file_path, 'w') do |file|
file.write("[")
if records.any?
last_id = records.last.id
records.find_each do |model|
file.write(model.to_json(except: excluded_columns))
file.write(",\n") if model.id != last_id
end
end
file.write("]\n")
end
@coorasse
Copy link
Author

coorasse commented Nov 17, 2021

JSON dumping solutions expect you to do something simpler like:

File.open(file_path, 'w') do |file|
  file.write(records.to_json(except: excluded_columns))
end

this will inevitably crash if your table contains millions of rows.

You can use the above script when dumping ActiveRecord tables for example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment