C++序列化json字元串對Unicode有哪些特殊處理?

C++庫json11(https://github.com/dropbox/json11)源碼中的一個問題.

對std::string代表的json字元串對象序列化函數如下:

static void dump(const string value, string out) {
out += ";
for (size_t i = 0; i &< value.length(); i++) { const char ch = value[i]; if (ch == \) { out += "\"; } else if (ch == ") { out += "\""; } else if (ch == ) { out += "\b"; } else if (ch == f) { out += "\f"; } else if (ch == ) { out += "\n"; } else if (ch == ) { out += "\r"; } else if (ch == ) { out += "\t"; } else if (static_cast&(ch) &<= 0x1f) { char buf[8]; snprintf(buf, sizeof buf, "\u%04x", ch); out += buf; } else if (static_cast&(ch) == 0xe2 static_cast&(value[i+1]) == 0x80
static_cast&(value[i+2]) == 0xa8) {
out += "\u2028";
i += 2;
} else if (static_cast&(ch) == 0xe2 static_cast&(value[i+1]) == 0x80
static_cast&(value[i+2]) == 0xa9) {
out += "\u2029";
i += 2;
} else {
out += ch;
}
}
out += ";
}

其中對於特殊字元 "  f

序列化時重新加上轉義字元可以理解.後續代碼中有兩個問題.

1. 後面對於unicode字元的處理中0x1f是什麼意思?

2.為什麼要單獨對unicode字元2028 2029進行處理?


根據 ECMA-404 [1] 第 7 節:

All characters may be
placed within the quotation marks except for the characters that must be escaped: quotation mark (U+0022),
reverse solidus (U+005C), and the control characters U+0000 to U+001F.

U+0000 至 U+001F 字元是必須轉義,當中除 BS、HT、LF、FF、CR 有特殊轉義符,其他都需要轉義成 "uXXXX" 的形式。

Any code point may be represented as a hexadecimal number.

所有碼點可以表示為"uXXXX" 形式。對於 U+2028 和 U+2029,[1] 並不要求轉義。可能是在某些應用中有此需求(如有bug)才需要進行轉義。但轉義是可以的。

[1] Intenational, Ecma. "The JSON Data Interchange Format." (2013). http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf


0000-001F 控制字元 保持原樣輸出

2028和2029可以查一下 為什麼說JSON非完全是JavaScript的子集 或 直接看http://stackoverflow.com/questions/16686687/json-stringify-and-u2028-u2029-check


value是utf8編碼的,Unicode中0000-001F
為C0控制符,直接輸出是不可顯示的,所以需要轉換為16進位。

U+2028 LINE SEPARATOR

U+2029 PARAGRAPH SEPARATOR

Why are there so many spaces and line breaks in Unicode?


推薦閱讀:

今天面試C++,機試面試官看完代碼說代碼結構混亂?
C++primer中一個疑似錯誤?
初學者學c++應該做什麼準備?
如何評價C++primer中文版(第五版)的翻譯?
應該以什麼心態和標準來學《 c++primer 》和 c++ ?

TAG:Unicode統一碼 | C | JSON |