T
T
TopClone2016-10-09 17:40:53
ruby
TopClone, 2016-10-09 17:40:53

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"

If anything, here is the JSON file itself:
{
"Apple":"Apple",
"Red":"Red",
"Milk":"Milk",
"Water":"Water",
"Sunrise":"Rise"
}

This is what I get from the console:
╨п╨▒╨╗╨╛╨║╨╛
╨Ъ╤A╨░╤B╨╜╤L╨╣
╨Ь╨╛╨╗╨╛╨║╨╛
╨Т╨╛╨┤╨T
_ ╤Б╤Е╨╛╨┤
Russian

Please help me fix it, thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
TopClone, 2016-10-09
@TopClone

Problem solved! It was just an oversight, you just had to add the encoding like this:

data = File.read('eng.json', encoding: 'utf-8')

C
Chronic 86, 2016-10-10
@chronic86

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 question

Ask a Question

731 491 924 answers to any question