Class: Decidim::Admin::Import::Readers::JSON
- Defined in:
- lib/decidim/admin/import/readers/json.rb
Overview
Imports any exported JSON file to local objects. It transforms the import data using the creator into the final target objects.
Constant Summary collapse
- MIME_TYPE =
"application/json"
Instance Method Summary collapse
-
#example_file(data) ⇒ Object
Returns a StringIO.
- #read_rows ⇒ Object
Methods inherited from Base
Constructor Details
This class inherits a constructor from Decidim::Admin::Import::Readers::Base
Instance Method Details
#example_file(data) ⇒ Object
Returns a StringIO
38 39 40 41 42 43 44 45 46 47 |
# File 'lib/decidim/admin/import/readers/json.rb', line 38 def example_file(data) columns = data.shift json_data = data.map do |row| deep_hash( columns.each_with_index.to_h { |col, ind| [col, row[ind]] } ) end ::StringIO.new(::JSON.pretty_generate(json_data)) end |
#read_rows ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/decidim/admin/import/readers/json.rb', line 14 def read_rows json_string = File.read(file) columns = [] data = ::JSON.parse(json_string) data.each_with_index do |row, index| row = flat_hash(row) if index.zero? columns = row.keys yield columns.map(&:to_s), index end values = columns.map { |c| row[c] } last_present = values.rindex { |v| !v.nil? } if last_present yield values[0..last_present], index + 1 else yield [], index + 1 end end rescue ::JSON::ParserError raise Decidim::Admin::Import::InvalidFileError, "The provided JSON file is not valid" end |