Maarten
Maarten

Reputation: 7308

Writing unicode json in Ruby

In Ruby 2.0.0, I want to write an array to json:

require 'json'
File.open('test.json', 'w') do |f2| 
  f2.puts ["£2M worth of wine"].to_json  
end  

This gives writes a file looking like this:

["£2M worth of wine"]

Obviously, not what I am looking for. Is this a bug in to_json? How can I make it work?

Upvotes: 0

Views: 802

Answers (1)

bjhaid
bjhaid

Reputation: 9762

You might want to force each element in the array to be encoded UTF-8 before calling to_json

e.g:

["£2M worth of wine"].map { |str| str.encode("utf-8") }.to_json

Upvotes: 2

Related Questions