控制JSON字符串中的字符

时间:2017-12-02 12:17:23

标签: json string escaping

控制必须转义的字符的JSON specification个状态仅包含U + 0000到U + 001F的代码:

7.  Strings

   The representation of strings is similar to conventions used in the C
   family of programming languages.  A string begins and ends with
   quotation marks.  All Unicode characters may be placed within the
   quotation marks, except for the characters that must be escaped:
   quotation mark, reverse solidus, and the control characters (U+0000
   through U+001F).

转义的主要思想是在终端或纸张上打印JSON文档或消息时不会损坏输出。

但还有其他控制字符,如[DEL] from C0 and other control characters from C1 set (U+0080 through U+009F)。难道他们也不能用JSON字符串进行转义吗?

1 个答案:

答案 0 :(得分:2)

来自JSON specification

setuptools.setup

在UTF-8中,127以上的所有代码点都以多个字节编码。这些字节中大约有一半是在C1控制字符范围内。因此,为了避免在UTF-8编码的JSON字符串中包含这些字节,所有这些代码点都需要进行转义。这有效地消除了UTF-8的使用,并且JSON字符串也可以用ASCII编码。由于ASCII是UTF-8的子集,因此标准不允许这样做。因此,如果你担心在字节流中放置C1控制字符只是为了逃避它们,但要求每个JSON表示使用ASCII在英语环境中的任何东西都会非常低效。

UTF-16和UTF-32不可能被使用C1(甚至C0)控制字符的东西解析,所以这些点对于那些编码来说是没有意义的。