Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby encoding issue with nested key

Tags:

ruby

In order to solve the problem with YAML incompatibility I'm trying to write a command-line script in Ruby. The problem it that I'm totally unfamiliar with Ruby.

So I've made the following script:

require 'json'
require 'yaml'

thing = YAML.load('--- 
author_id: 
- 0
- 1
subject: 
- ""
- !binary |
  0KHQtNC10LvQsNGC0Ywg0LPRgNCw0LzQvtGC0L3Ri9C5INCy0L3QtdGI0L3Q
  uNC5INCy0LjQtCDQtNC70Y8g0LjQvNC10Y7RidC10LPQvtGB0Y8=
')

puts thing.to_json
# puts thing['subject'][1].to_json # Issues the same error

And now I'm getting yaml2json.rb:15:inencode': "\xD0" from ASCII-8BIT to UTF-8 (Encoding::UndefinedConversionError)`

How to make it think that the decoded base64 is in UTF-8? Generally I don't know the exact name of a key, subject is only an example.

like image 596
Pavel Koryagin Avatar asked Oct 05 '22 07:10

Pavel Koryagin


1 Answers

thing['subject'][1].force_encoding('utf-8')
puts thing.to_json

Produces:

{"author_id":[0,1],"subject":["","Сделать грамотный внешний вид для имеющегося"]}

Since you don't know where the strings will be, the best option that comes to mind at the moment is to recursively traverse the Hash, force_encoding all strings. There may be a more elegant solution.

like image 110
Darshan Rivka Whittle Avatar answered Oct 13 '22 11:10

Darshan Rivka Whittle