0

I have a controller index method that renders html and json:

def index
  @articles = Article.all
  respond_to do |format|
    format.html
    format.json { render text: @articles.to_json }
  end
end

In my html, everything works fine, names are displayed as Müller (with a german umlaut). However, when I render json, I get weird characters like M\u00fcller.

When I look at the encoding of the title attribute in my Article model, it returns UTF-8:

puts @articles.first.attributes["title"]
=> "Müller"
puts @articles.first.attributes["title"].encoding
=> #<Encoding:UTF-8>

But when I convert it into json, I get wrong characters:

puts @articles.first.attributes.to_json
=> "{\"id\":293,\"title\":\"M\\u00fcller\"}"

I'm not sure why this only happens for json. I'm using Rails 3.2.9.

23tux
  • 14,104
  • 15
  • 88
  • 187
  • Have you tried [these](http://stackoverflow.com/questions/5123993/json-encoding-wrongly-escaped-rails-3-ruby-1-9-2) solutions? – Leo Brito Dec 17 '15 at 13:47
  • Yes, I've found that, and it solves my problem. But I thought there would be a better, not hacky solution – 23tux Dec 17 '15 at 13:55
  • Just thinking out loud here: I guess `to_json` is *supposed to* escape chars so that the resulting json can travel well wherever it goes, while unescaping depends primarily on the client, and as such should be done on a higher level. – Leo Brito Dec 17 '15 at 14:00

1 Answers1

0

Your render call is rendering your JSON document explicitly as text, which is likely the source of your problem. Try this instead:

format.json { render json: @articles.as_json }

This will go through the normal Rails JSON encoding path, which is very much intended to properly handle UTF-8.

P.S. For your code examples, those don't look like the output of puts calls but instead the output of IRB's representation of values -- in which case, the escaping of UTF-8 characters is happening simply so that IRB can render you a pastable-back-into-IRB version of your string.

Robert Nubel
  • 7,104
  • 1
  • 18
  • 30