Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
746 views
in Technique[技术] by (71.8m points)

javascript - Shouldn't JSON.stringify escape Unicode characters?

I have a simple test page in UTF-8 where text with letters in multiple different languages gets stringified to JSON:

http://jsfiddle.net/Mhgy5/

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:

?$("#encode").click(function () {
    $("#out").text(JSON.stringify({ txt: $("#txt").val() }));
}).click();
?

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 ? ?????
"}

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?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 string format


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...