Answer the question
In order to leave comments, you need to log in
How to fix encoding problem in Ruby?
There is a problem with encodings when you output keys from an associative array that takes information from a JSON file, but Russian characters work with just "puts".
if (Gem.win_platform?)
Encoding.default_external = Encoding.find(Encoding.locale_charmap)
Encoding.default_internal = __ENCODING__
[STDIN, STDOUT].each do |io|
io.set_encoding(Encoding.default_external, Encoding.default_internal)
end
end
require "json"
data = File.read('eng.json')
data_hash = JSON.parse(data)
data_hash.each_key {|key| puts key }
puts "Russian"
{
"Apple":"Apple",
"Red":"Red",
"Milk":"Milk",
"Water":"Water",
"Sunrise":"Rise"
}
╨п╨▒╨╗╨╛╨║╨╛
╨Ъ╤A╨░╤B╨╜╤L╨╣
╨Ь╨╛╨╗╨╛╨║╨╛
╨Т╨╛╨┤╨T
_ ╤Б╤Е╨╛╨┤
Russian
Answer the question
In order to leave comments, you need to log in
Problem solved! It was just an oversight, you just had to add the encoding like this:
data = File.read('eng.json', encoding: 'utf-8')
You can alternatively use a record at the beginning of the file.
# encoding: utf-8
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question