when python loads json,how to convert str to unicode ,so I can print Chinese characters? -
i got json file this:
{ 'errnum': 0, 'retdata': { 'city': "武汉" } } import json content = json.loads(result) # supposing json file named result cityname = content['retdata']['city'] print cityname
after that, got output : \u6b66\u6c49
know it's unicode of chinese character of 武汉
,but type of str isinstance(cityname,str)
true. how can convert str unicode , output 武汉
i have tried these solutions:
>>> u'\u6b66\u6c49' u'\u6b66\u6c49' >>> print u'\u6b66\u6c49' 武汉 >>> print '\u6b66\u6c49'.decode() \u6b66\u6c49 >>> print '\u6b66\u6c49' \u6b66\u6c49
searched ascii,unicode , utf-8 ,encode , decode ,but cannot understand,it crazy! need ,thanks !
your json contains escaped unicode characters. can decode them actual unicode characters using unicode_escape
codec:
print cityname.decode('unicode_escape')
note that, while work, depending on source of unicode escaping have problems characters outside basic multilingual plane (u+0 u+ffff). convenient quote user @bobince took comment:
note ... there number of different formats use \u escapes - python unicode literals (which unicode-escape handles), java properties, javascript string literals, json, , on. important know 1 dealing because have different rules other escapes valid. unicode-escape may or may not valid way of parsing data depending on comes from.
Comments
Post a Comment