【问题标题】:Why does this Unicode / UTF-8 "En Dash" character in my JSON feed get mangled when I download it?为什么我的 JSON 提要中的这个 Unicode / UTF-8 “En Dash”字符在我下载它时会被破坏?
【发布时间】:2014-05-08 04:31:07
【问题描述】:

我的 JSON 提要在这里:

http://america.aljazeera.com/bin/ajam/api/story.json?path=/content/ajam/watch/shows/america-tonight/articles/2014/4/28/the-dark-side-oftheoilboomhumantraffickingintheheartland

这是该 HTML 页面的 JSON 表示,您可以在页面的副标题中看到相同的 En Dash 字符。

http://america.aljazeera.com/watch/shows/america-tonight/articles/2014/4/28/the-dark-side-oftheoilboomhumantraffickingintheheartland.html

En Dash 在第二个键(描述)中:

description: "In a North Dakota town that was once dying, oil and money are flowing – and bringing big-city problems",

在“流”字之后。

该页面具有以下 HTTP 标头:

Content-Type: application/json;charset=UTF-8

可以通过curl -vcurl -I请求查看

像这样使用 HTTParty 在 Ruby 中下载它:

> r = HTTParty.get('http://america.aljazeera.com/bin/ajam/api/story.json?path=/content/ajam/watch/shows/america-tonight/articles/2014/4/28/the-dark-side-oftheoilboomhumantraffickingintheheartland')
> r['description']
 => "In a North Dakota town that was once dying, oil and money are flowing –\u0080\u0093 and bringing big-city problems"

破坏它,如上所示。经过大量研究,我意识到这是十六进制 utf-8 unicode 值的表示,如下所示:

http://www.fileformat.info/info/unicode/char/2013/index.htm

具体来说,这个:

UTF-8 (hex) 0xE2 0x80 0x93 (e28093)

这些数据稍后会被输入到 iPhone 应用和 Android 应用中。在 Android 应用程序上,它看起来像附加的。在 iPhone 上它看起来不错 - 我认为因为只有第一个字符被渲染,这是一个常规的 Ascii 破折号,接下来的两个字符被跳过。

最后,使用 AJAX 在 JavaScript 中下载它似乎可以正确处理它:

> r = json['description'].match(/flowing (.*) and/)[1]
> "–"
> r
> "–"
> r.length
> 3
> r.toString(16)
> "–"

那么……这是怎么回事?我能做些什么来修复它?是服务器有问题还是我的代码有问题?

【问题讨论】:

  • 它没有被“破坏”,这正是 JSON 的工作方式。使用标准 JSON 库来操作它。
  • 我明白了。下载后,我做了一些转换,然后在这里公开:d3e8cn1r5u4e7p.cloudfront.net/api/simple?page=6 Android 应用程序从那里下载它。然后 android 应用程序显示它 - 如屏幕截图所示 - 不太好。那么这是否意味着该错误存在于 Android 应用中?

标签: ruby unicode utf-8 character-encoding httparty


【解决方案1】:

您使用的 JSON 提要未能正确解释 \u2013。而不是生成所需的 UTF-8 编码字节序列:

E2 80 93

它生成了:

E2 80 93 C2 80 C2 93

iPhone 应用程序运行良好的原因可能是它忽略了控制字符C2 80C2 93。然而,Android 应用程序只是将其呈现为一些特殊的图形。

如果您无法控制 JSON 提要,则需要手动清除这些错误序列。

【讨论】:

  • +1 确认 Feed 已损坏。您可以尝试转码为 ISO-8859-1,然后将这些字节重新解释为 UTF-8 来修复它,但最好向网站管理员报告并尝试让他们解决。
  • 谢谢,这很有帮助。您如何确定发送的实际字节数? (或者更重要的是,我该怎么做?)
  • @Gal 通过 wget 或浏览器获取响应,保存到文件,并使用一些十六进制编辑器检查字节序列,例如 UltraEditor 或 vim + xxd。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-26
  • 2021-03-07
  • 1970-01-01
  • 2018-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多