加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在ruby中处理来自json的坏UTF-8

发布时间:2020-12-17 03:21:56 所属栏目:百科 来源:网络整理
导读:我在 http://hndroidapi.appspot.com/news/format/json/page/?appid=test从远程json中提取数据.我遇到的问题是这个API似乎正在构建JSON而没有正确处理UTF-8编码(如果我在这里错了,请纠正我).例如,现在传递的部分结果是 {"title":"IPad - please doneuro;trad
我在 http://hndroidapi.appspot.com/news/format/json/page/?appid=test从远程json中提取数据.我遇到的问题是这个API似乎正在构建JSON而没有正确处理UTF-8编码(如果我在这里错了,请纠正我).例如,现在传递的部分结果是

{
"title":"IPad - please don€™t ding while you and I are asleep  ","url":"http://modern-products.tumblr.com/post/25384729998/ipad-please-dont-ding-while-you-and-i-are-asleep","score":"10 points","user":"roee","comments":"18 comments","time":"1 hour ago","item_id":"4128497","description":"10 points by roee 1 hour ago  | 18 comments"
}

请注意don& euro;& trade; t.而这并不是它窒息的唯一一种角色.鉴于我不控制API,有什么办法可以将数据转换为干净的东西吗?

编辑:

这是我如何拉下JSON:

hn_url = "http://hndroidapi.appspot.com/news/format/json/page/?appid=test"
  url = URI.parse(hn_url)

  # Attempt to get the json
  req = Net::HTTP::Get.new(hn_url)
  req.add_field('User-Agent','Test')
  res = Net::HTTP.start(url.host,url.port) {|http| http.request(req) }
  response = res.body
  if response.nil?
    puts "Bad response when fetching HN json"
    return
  end

  # Attempt to parse the json
  result = JSON.parse(response)
  if result.nil?
    puts "Error parsing HN json"
    return
  end

编辑2:

刚刚找到了API的GitHub页面.看起来这是一个突出的问题.仍然不确定我是否可以从我的结果做任何变通办法:
https://github.com/glebpopov/Hacker-News-Droid-API/issues/4

解决方法

看起来您正在接收的JSON响应正文是以US-ASCII而不是UTF-8接收的,因为Net :: HTTP故意不强制编码.

1.9.3p194 :044 > puts res.body.encoding
US-ASCII

在Ruby 1.9.3中,如果你知道它应该是什么,你可以强制编码.试试这个:

response = res.body.force_encoding('UTF-8')

然后,JSON解析器应该按照您希望的方式处理UTF-8.

参考

> http://bugs.ruby-lang.org/ – Net::HTTP does not handle encoding correctly

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读