Skip to content

Instantly share code, notes, and snippets.

@haslo
Last active October 26, 2016 12:26
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 haslo/0434bd4c1e94c45bb8cc747e73e4e5a7 to your computer and use it in GitHub Desktop.
Save haslo/0434bd4c1e94c45bb8cc747e73e4e5a7 to your computer and use it in GitHub Desktop.
Exports a nested JSON into an Excel, to send to clients for translations
#!/usr/bin/env ruby
require 'json'
require 'spreadsheet'
def process_hash(translations, current_key, hash)
hash.each do |new_key, value|
combined_key = [current_key, new_key].delete_if { |k| k == '' }.join(".")
if value.is_a?(Hash)
process_hash(translations, combined_key, value)
else
translations[combined_key] = value
end
end
end
def json_to_list(filename)
file_content = File.read(filename)
json_content = JSON.parse(file_content)
translations = {}
process_hash(translations, '', json_content)
translations
end
def generate_excel(translations)
Spreadsheet.client_encoding = 'UTF-8'
workbook = Spreadsheet::Workbook.new
sheet = workbook.create_worksheet
sheet.name = 'Texte'
title_format = Spreadsheet::Format.new(weight: :bold)
# you might need to change this?
sheet.row(0).push 'Schlüssel', 'de', 'fr', 'it?', 'en?'
sheet.row(0).default_format = title_format
current_row = 1
translations.each do |translation_key, translated_string|
sheet.row(current_row).push translation_key, translated_string
current_row += 1
end
workbook
end
translations = json_to_list('<input filename>.json')
workbook = generate_excel(translations)
filename = '<output filename>.xls'
File.delete(filename) if File.exist?(filename)
workbook.write filename
@haslo
Copy link
Author

haslo commented Oct 26, 2016

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