Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert JSON translations strings into an awesome CSV document
require 'json'
require 'csv'
class Key
attr_reader :file, :key, :translations
def initialize(file, key)
@file = file
@key = key
@translations = {}
end
def add_translation(language, value)
@translations[language] = value
end
end
class LanguageJsonToCsv
def initialize
@languages = []
@keys = []
load_language_files
generate_csv_file
end
private
def load_language_files
json_files.each do |file|
name = File.basename(file, '.json')
if name.include?('.')
name, language = name.split('.')
else
language = name
name = nil
end
@languages << language unless @languages.include?(language)
content = load_json(file)[language]
dot_flatten_hash(content).each do |k, v|
key = @keys.find { |e| e.key == k }
unless key
key = Key.new(name, k)
@keys << key
end
key.add_translation(language, v)
end
end
end
def generate_csv_file
CSV.open(output_file, 'wb', csv_options) do |csv|
csv << csv_header
@keys.each do |key|
data = [key.file, key.key]
@languages.each do |language|
if key.translations[language]
data << key.translations[language]
else
data << '---'
end
end
csv << data
end
end
end
def load_json(path)
file = File.read(path)
JSON.parse(file)
end
def dot_flatten_hash(hash, prefix = '')
new_hash = {}
hash.keys.each do |key|
prefix_string = prefix.empty? ? '' : "#{prefix}."
if hash[key].is_a?(Hash)
new_hash.merge!(dot_flatten_hash(hash[key], "#{prefix_string}#{key}"))
else
new_hash["#{prefix_string}#{key}"] = hash[key]
end
end
new_hash
end
def current_dir
File.expand_path('..', __FILE__)
end
def json_files
Dir["#{current_dir}/**/*.json"]
end
def output_file
File.expand_path('../translations.csv', __FILE__)
end
def csv_header
%w(File Key) + @languages.map(&:upcase)
end
def csv_options
{ force_quotes: true }
end
end
LanguageJsonToCsv.new
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.