编码::UndefinedConversionError "\xE7" 从 ASCII-8BIT 到 UTF-8

Bib*_*rma 2 ruby macos encoding ruby-on-rails utf-8

我正在开发一个 Rails API 项目。这是我的代码片段

class PeopleController < ApplicationController
  respond_to :json

  def index
    respond_with Person.all
  end
end
Run Code Online (Sandbox Code Playgroud)

当我访问该网址时localhost:3000/people.json

Encoding::UndefinedConversionError at /people.json
"\xE7" from ASCII-8BIT to UTF-8
Run Code Online (Sandbox Code Playgroud)

自上周以来我一直在努力解决这个问题,但仍在努力解决这个问题。我在 stackoverflow 上发现了一堆类似的问题,例如this & this,但没有一个解决方案对我有用。

这是我的配置。

导轨 4.2.7.1

红宝石-2.3.1

操作系统:macOS Sierra

输出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=
Run Code Online (Sandbox Code Playgroud)

内容于 ~/.bash_profile

export LC_CTYPE="utf-8"
export LC_CTYPE=en_US.UTF-8
export LANG=en_US.UTF-8
unset LC_ALL
Run Code Online (Sandbox Code Playgroud)

输出 Encoding.default_external

 #<Encoding:UTF-8> 
Run Code Online (Sandbox Code Playgroud)

Sev*_*rin 5

我已经多次遇到这个问题,所以我通常会尝试在将 UTF-8 保存到数据库之前删除任何对 UTF-8 无效的字符。如果您将记录保存为 a,String则可以替换无效字符,如下所示:

\n\n
string = "This contains an invalid character \\xE7"\nstring.encode(\'UTF-8\', invalid: :replace, undef: :replace)\n#=> "This contains an invalid character \xef\xbf\xbd"\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是在将其转换为 JSON 对象之前的情况。

\n