Last active
February 22, 2019 12:12
-
-
Save wolivera/e057a796416088481c5ababf8ce049a1 to your computer and use it in GitHub Desktop.
Task to read, write and save a JSON file in Ruby
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
namespace :json do | |
# Usage: rake json:set_fields[file_name] | |
desc "Set some sample fields to an existing JSON file" | |
task :set_fields, [:file_name] => :environment do |t, args| | |
file_name = args[:file_name] | |
file_folder = Rails.root.join('app','assets','sample') # Step over the right folder | |
file = File.read(file_folder.join(file_name + ".json")) # Get the JSON file | |
fields = JSON.parse(form) # Get the JSON data to parse | |
updated_fields = set_fields(fields) # Set required to ruby Hash | |
File.open(file_folder.join(form_name + ".json"), "w") do |f| # Open the file to write | |
f.puts JSON.pretty_generate(updated_fields) # Write the updated JSON | |
end | |
end | |
def set_fields(fields) | |
fields.each do |field| | |
field["somekey"]["someproperty"] = true | |
end | |
fields | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment