user081608
user081608

Reputation: 1113

Merging multiple JSON files onto one Ruby file

I am trying to read multiple JSON files and merge them in a ruby file. Here is what I currently have for one that works:

require 'json'  
file = File.read(File.dirname(File.expand_path(__FILE__)) + '/../attributes.json')  
default.merge! JSON.parse(file)

Now if I have the following directory structure where the attributes.json is:

attributes.json
Prod
  -JSON1.json
  -JSON2.json
Test
  -JSON1.json
  -JSON2.json

How would I accomplish reading all these JSON files on the one ruby file?I am assuming some sort of recursive loop but I can not figure it out.

Upvotes: 0

Views: 1367

Answers (1)

user081608
user081608

Reputation: 1113

I figured out my answer. Here is what I ended up doing:

Find.find('/path/to/directory/') do |f|
   next if File.extname(f) != ".json"
   file = File.read(f)
   default.merge! JSON.parse(file)
end

I used Find which will search for files in any directory and then pass on the file id it does not have a .json extension.

Upvotes: 2

Related Questions