JSON.stringify是否不转义Unicode字符? [英] Shouldn't JSON.stringify escape Unicode characters?
问题描述
我在UTF-8中有一个简单的测试页,其中带有多种不同语言字母的文本被字符串化为JSON:
I have a simple test page in UTF-8 where text with letters in multiple different languages gets stringified to JSON:
HTML:
<textarea id="txt">
検索 • Busca • Sök • 搜尋 • Tìm kiếm • Пошук • Cerca • Søk • Haku • Hledání • Keresés • 찾기 • Cari • Ara • جستجو • Căutare • بحث • Hľadať • Søg • Serĉu • Претрага • Paieška • Poišči • Cari • חיפוש • Търсене • Іздеу • Bilatu • Suk • Bilnga • Traži • खोजें
</textarea>
<button id="encode">Encode</button>
<pre id="out">
</pre>
JavaScript:
JavaScript:
$("#encode").click(function () {
$("#out").text(JSON.stringify({ txt: $("#txt").val() }));
}).click();
尽管我希望根据 JSON规范将非ASCII字符转义为\ uXXXX,但它们似乎没有被修改.这是我从上述测试中获得的输出:
While I expect the non-ASCII characters to be escaped as \uXXXX as per the JSON spec, they seem to be untouched. Here's the output I get from the above test:
{"txt":"検索 • Busca • Sök • 搜尋 • Tìm kiếm • Пошук • Cerca • Søk • Haku • Hledání • Keresés • 찾기 • Cari • Ara • جستجو • Căutare • بحث • Hľadať • Søg • Serĉu • Претрага • Paieška • Poišči • Cari • חיפוש • Търсене • Іздеу • Bilatu • Suk • Bilnga • Traži • खोजें\n"}
我正在使用Chrome,因此它应该是本机JSON.stringify
实施.页面的编码为UTF-8.非ASCII字符不应该转义吗?
I'm using Chrome, so it should be the native JSON.stringify
implementation. The page's encoding is UTF-8. Shouldn't the non-ASCII characters be escaped?
首先让我参加此测试的是,我注意到jQuery.ajax
出现在数据对象属性中时,似乎没有转义非ASCII字符.这些字符似乎是以UTF-8格式传输的.
What brought me to this test in the first place is, I noticed that jQuery.ajax
doesn't seem to escape non-ASCII characters when they appear in a data object property. The characters seem to be transmitted as UTF-8.
推荐答案
JSON规范不需要从Unicode字符转义序列. 除或\或控制字符外的任何UNICODE字符."被定义为有效的JSON序列化字符串:
The JSON spec does not demand the conversion from unicode characters to escape-sequences. "Any UNICODE character except " or \ or control character." is defined to be a valid JSON-serialized string:
这篇关于JSON.stringify是否不转义Unicode字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!