JS无法解析具有Unicode字符的JSON [英] JS cannot parse JSON with unicode character
问题描述
我具有以下JSON字符串{"name":""C\u008cUR Carmen"}
,但未解析\u008c
.而是显示空字符.
I have the following JSON string {"name":""C\u008cUR Carmen"}
but \u008c
is not parsed. It shows empty character instead.
json = '{"name":"C\u008cUR Carmen"}';
json = JSON && JSON.parse(json) || $.parseJSON(json);
显示:CUR Carmen
期望:CŒUR Carmen
请帮助.
*注* :JSON数据由PHP服务器返回,因此不会出现任何语法错误,因为我使用了json_encode
并从AJAX获得了响应.它可以与其他字符(例如à, é
)一起使用,但只有此奇怪的字符不能正确显示
* Note * : The JSON data is returned by the PHP server so there shouldn't be any syntax error because I used json_encode
and get the response from AJAX. It works with other characters such as à, é
but only this wierd character doesn't display properly
编辑:已解决!这不是JS问题,而是MySQL返回的字符集问题.您可以在返回SQL数据之前使用mysql_set_charset('utf8')
.按预期显示\u0152
EDIT : Solved! It's not a JS problem it's a charset problem returned by MySQL. You can use mysql_set_charset('utf8')
before returning SQL data. Show \u0152
as expected
推荐答案
无需转义 RFC 4627
2.5.字符串
字符串的表示类似于C语言中使用的约定 编程语言家族.字符串以开头和结尾 引号.所有Unicode字符都可以放在 用引号引起来,但必须转义的字符除外: 引号,反固相线和控制字符(U + 0000 通过U + 001F).
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).
您可以直接使用unicode字符串:
You can use your unicode string directly:
json = '{"name":"CŒUR Carmen"}';
json = JSON && JSON.parse(json) || $.parseJSON(json);
我认为您的服务器端实现中存在一个代码转换错误,您在使用json_encode
之前将输出更改为ASCII. JSON要求所有数据均以Unicode编码.
I think there's a transcoding bug in your server side implementation where you change the output to ASCII before using json_encode
. It is a requirement of JSON that all data is encoded in Unicode.
修改
在此小提琴中,有一个示例如何在javascript中还原转义的unicode.
In this fiddle there's an example how to revert the escaped unicode in javascript.
这篇关于JS无法解析具有Unicode字符的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!