I am writing a webservice that uses json to represent its resources, and I am a bit stuck thinking about the best way to encode the json. Reading the json rfc (http://www.ietf.org/rfc/rfc4627.txt) it is clear that the preferred encoding is utf-8. But the rfc also describes a string escaping mechanism for specifying characters. I assume this would generally be used to escape non-ascii characters, thereby making the resulting utf-8 valid ascii.

So let's say I have a json string that contains unicode characters (code-points) that are non-ascii. Should my webservice just utf-8 encoding that and return it, or should it escape all those non-ascii characters and return pure ascii?

我希望浏览器能够使用JSONP或eval执行结果.这会影响这个决定吗?我对各种浏览器对utf-8的javascript支持缺乏了解.

编辑:我想澄清一下,我主要关心的是如何对结果进行编码,实际上是浏览器对结果的处理.我读到的内容表明,浏览器在使用JSONP时可能对编码非常敏感.我还没有找到任何关于这个主题的好信息,所以我必须开始做一些测试,看看会发生什么.理想情况下,我只想转义所需的几个字符,并对结果进行utf-8编码.

推荐答案

解码器支持JSON SPEC requires UTF-8.因此,所有JSON解码器都可以像处理数字转义序列一样处理UTF-8.Javascript解释器也是如此,这意味着JSONP也将处理UTF-8编码的JSON.

The ability for JSON encoders to use the numeric escape sequences instead just offers you more choice. One reason you may choose the numeric escape sequences would be if a transport mechanism in between your encoder and the intended decoder is not binary-safe.

Another reason you may want to use numeric escape sequences is to prevent certain characters appearing in the stream, such as <, & and ", which may be interpreted as HTML sequences if the JSON code is placed without escaping into HTML or a browser wrongly interprets it as HTML. This can be a defence against HTML injection or cross-site scripting (note: some characters MUST be escaped in JSON, including " and \).

有些框架,包括PHP的json_encode()(默认情况下),always在编码器端对ASCII之外的任何字符执行数字转义序列.这是一个基本上不必要的额外步骤,旨在最大限度地兼容有限的传输机制等.然而,这不应被解释为任何JSON解码器都存在UTF-8问题.

So, I guess you just could decide which to use like this:

  • 只需使用UTF-8,除非用于编码器和解码器之间存储或传输的任何软件都不是二进制安全的.

  • 否则,请使用数字转义序列.

Json相关问答推荐

将数据从嵌套的SON数组提取到更简单的数组中

将json数组反序列化为选项 struct

Golang JSON Date Tim.Date()测试请求

如何使NiFi将数据库单列中的多个值转化为Solr索引中的数组?

如何在 Apache NiFi 中使用 JoltTransformJson 删除流文件或具有空字段的整个对象?

无法使用 vue.js 访问 JSON 数组的项目

使用 jq 将消息转换为数组

在 PostgreSQL 中 Select 分层 JSON 作为表

我如何将 JSON 格式与 flutter 一起使用?帮助使用 Gamebanana api

判断golang中解析的json响应中是否存在所需的json键(不是值)

在 Flutter 中将对象转换为可编码对象失败

使用 json_query 过滤嵌套列表中的元素

Microsoft GRAPH 查询使用端点 /deviceManagement/deviceHealthScripts 列出了一种不熟悉的检测脚本内容格式

将 ES6 类对象序列化为 JSON

苗条的 JSON 输出

使用 JSON 的 javascript 深拷贝

使用 JSON.Net 的 C# 到 JSON 序列化

如何安装 json gem - 无法构建 gem 原生扩展(mac 10.10)

将循环 struct 转换为 JSON - 有什么方法可以找到它抱怨的字段?

MySQL Select JSON 字段属性具有值的位置