我在尝试将推文写入我的 psql 数据库时遇到错误。
我在互联网上到处搜索(可能不够好)寻找答案,但无济于事。我在这里查看了答案 - 但建议是将字符串转换为 UTF8(即使响应 header 声称它已经是 UTF-8)。
我是用这段代码这样做的:
# get the data from twitter
response = RestClient.get "http://search.twitter.com/search.json?rpp=100&since_id=238726971826253824&q=love"
# find the data encoding using CharDet
data = CharDet.detect(response.body)
encoding = data['encoding']
# create a new instance of Iconv with UTF-8 and then convert response.body
ic = Iconv.new('UTF-8//IGNORE', encoding)
converted_response = ic.iconv(response.body + ' ')[0..-2]
# take the data and convert it to JSON
response_json = ActiveSupport::JSON.decode(converted_response)
然后我们解析 response_json 并在数据库中创建推文。但是,这样做时,我们会在下面收到此错误。
[4;36;1mSQL (0.1ms)[0m [0;1mBEGIN[0m
[4;35;1mSQL (0.0ms)[0m [0mPG::Error: ERROR: invalid byte sequence for encoding "UTF8": 0xeda0bc
: INSERT INTO "tweets" ("from_user_id", "approved", "from_user", "has_profanity", "twitter_search_id", "twitter_id", "posted_at", "updated_at", "iso_language_code", "profile_image_url", "text", "created_at", "archived", "geo", "to_user_id", "to_user", "metadata", "source", "event_id") VALUES(573857675, NULL, 'nataliekiro', NULL, 618, 238825898718162944, '2012-08-24 02:31:46.000000', '2012-08-24 02:32:05.166492', 'en', 'http://a0.twimg.com/profile_images/2341785780/image_normal.jpg', 'Happy Birthday @daughternumber1 í ¼í¾‚ Love You í ½í¸˜', '2012-08-24 02:32:05.166492', 'f', NULL, 0, NULL,
'--- !map:HashWithIndifferentAccess
result_type: recent
我已经继续测试 response_json 的类(返回哈希),即使在该错误结束时它说 HashWithIndifferentAccess。
其他人有类似的问题并知道解决方案吗?
谢谢!
最佳答案
我找到了一个有效的解决方案!不确定这是否是最好的示例,因为我是 Rails/Ruby 的新手 - 但它似乎至少暂时有效!
如您在上面的示例中所见,我试图将整个 response.body 转换为 UTF-8。事实证明这是不成功的。
在查看正在检索的数据时,唯一可能具有非 UTF-8 实体的部分是推文状态文本。 Twitter 不允许在其显示名称中使用非 a-z、-、_ 字符。由于我只存储显示名称、状态文本和推文 ID,因此留下了状态文本。查看从 Twitter 中提取的一些状态 - 一些用户在他们的推文中使用表情符号等。
我的解决方案是将单个状态文本转换为 UTF-8,然后在哈希中重新分配它。
def parse_response!
tweets_json = response_json['results'].reverse rescue []
tweets << tweets_json.collect do |tweet_json|
# trying to fix encoding issue!
data = CharDet.detect(tweet_json['text'])
encoding = data['encoding']
ic = Iconv.new('UTF-8//IGNORE', encoding)
converted_response = ic.iconv(tweet_json['text'] + ' ')[0..-2]
# after converting, put back into value
tweet_json['text'] = converted_response
# ... etc
谈谈学习过程!
感谢@CraigRinger 的帮助!
关于ruby-on-rails - Rails 0mPG::错误:错误:编码 "UTF8"的字节序列无效:0xeda0bc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12102629/