简体   繁体   中英

Encoding::UndefinedConversionError "\xE7" from ASCII-8BIT to UTF-8

I'm working on a rails API project. Here is my code snippets

class PeopleController < ApplicationController
  respond_to :json

  def index
    respond_with Person.all
  end
end

and when I visit the url localhost:3000/people.json

 Encoding::UndefinedConversionError at /people.json "\\xE7" from ASCII-8BIT to UTF-8

I'm trying to solve this issue since last week, but still fighting with this. I've found the bunch of similar question over stackoverflow such as this & this but non of the solution worked for me.

Here are the configuration I've.

Rails 4.2.7.1

ruby-2.3.1

Operating system: macOS Sierra

Output of locale

LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL=

content on ~/.bash_profile

export LC_CTYPE="utf-8"
export LC_CTYPE=en_US.UTF-8
export LANG=en_US.UTF-8
unset LC_ALL

Output of Encoding.default_external

 #<Encoding:UTF-8> 

I have had this problem a lot of times, so I usually try to get rid of any characters that are invalid to UTF-8 BEFORE saving it in the Database. If you have your record saved as a String you can replace invalid characters like so:

string = "This contains an invalid character \xE7"
string.encode('UTF-8', invalid: :replace, undef: :replace)
#=> "This contains an invalid character �"

This is ofc prior to converting it to a JSON object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM