json - 如何通过 HTTP 发送 Unicode JSON?

标签 json http unicode encoding utf-8

RFC 4627第 3 节说

JSON text SHALL be encoded in Unicode. The default encoding is UTF-8.

Since the first two characters of a JSON text will always be ASCII characters [RFC0020], it is possible to determine whether an octet stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking at the pattern of nulls in the first four octets.

       00 00 00 xx  UTF-32BE
       00 xx 00 xx  UTF-16BE
       xx 00 00 00  UTF-32LE
       xx 00 xx 00  UTF-16LE
       xx xx xx xx  UTF-8

我正在提供 UTF-8 编码的 JSON 字符串 U+20AC作为应用程序/json。

$ curl -D - http://localhost:8000/test.json
HTTP/1.0 200 OK
Server: SimpleHTTP/0.6 Python/2.7.6
Date: Fri, 15 Jan 2016 09:24:53 GMT
Content-type: application/json
Content-Length: 6
Last-Modified: Fri, 15 Jan 2016 09:23:13 GMT

"€"

$ curl -s http://localhost:8000/test.json | hexdump
0000000 e222 ac82 0a22                         
0000006

但是 Chrome Firefox 似乎都在使用其他编码,正如两者所示

"€"

如果将Content-Type更改为application/json; charset=utf-8,它们显示了预期的结果。

但是 charset 是对 application/json 的补充,我不确定向其中添加额外参数是否合法。

这一切都相当令人困惑。

有什么地方有错误吗?通过 HTTP 传输 UTF-8 编码的 JSON 文档的正确方法是什么?

最佳答案

您的回答是正确的。 charset 不应该对 application/json 执行任何操作,因为它是 text/ 类型的参数; JSON 处理器将忽略它。

问题是 Chrome 和 Firefox 在这里并没有充当 JSON 处理器;而是充当 JSON 处理器。他们不会解析或验证响应内容中的任何内容。他们正在退回到常规的旧文本查看器,将内容显示为 text/plain,前提是这总比没有好。

不幸的是,纯文本查看器有自己的猜测编码规则,这些规则与 JSON 的仅内容内信令规则不匹配。 IE 将 application/json 视为未知的二进制类型并提示您下载它的行为实际上是更正确的做法。

关于json - 如何通过 HTTP 发送 Unicode JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34808136/

相关文章:

php - 带有委托(delegate)的 PHP 中的异步 HTTP 请求

mysql - PHP/MySQL 中的 Unicode 比较

python - unicodedata.normalize 缺少一个字符进行转换

python - python中的Unicode编码

javascript - Highcharts 仪表在通过 json 获取数据之前渲染

java - 接口(interface)中的 Pojo

javascript - 带有 ng-scroll 和 ng-repeat 的 AngularJS

javascript - getJSON 超时处理

http - 在 HTTP 202 响应中使用 Location header 是否符合 RFC 标准?

javascript - Angularjs - 我得到了 data.data,但无法为其分配范围变量