python3的编码问题一直比较简单
内存中字符串采用unicode
存储到文件中采用utf-8
以下为str,byte互相转换的过程:
str = "abc学习"strOut[6]: ‘abc学习‘mybyte = str.encode("utf-8")mybyteOut[8]: b‘abc\xe5\xad\xa6\xe4\xb9\xa0‘str2 = mybyte.decode("utf-8")str2Out[10]: ‘abc学习‘
最近在写json相关的文件存取,遇到这样的问题:
import jsonjson_str = """{"a": " 1", "f": "100\n", "b": "好好学习"}"""json_strOut[20]: ‘{"a": " 1", "f": "100\n", "b": "好好学习"}‘json_str = json_str.encode(‘unicode_escape‘).decode(‘utf-8‘)json_strOut[22]: ‘{"a": " 1", "f": "100\\n", "b": "\\u597d\\u597d\\u5b66\\u4e60"}‘json_data = json.loads(json_str, encoding="utf-8")json_dataOut[24]: {‘a‘: ‘ 1‘, ‘b‘: ‘好好学习‘, ‘f‘: ‘100\n‘}dumps_str = json.dumps(json_data, indent=4)dumps_strOut[26]: ‘{\n "f": "100\\n",\n "a": " 1",\n "b": "\\u597d\\u597d\\u5b66\\u4e60"\n}‘json_data = json.loads(dumps_str)json_dataOut[28]: {‘a‘: ‘ 1‘, ‘b‘: ‘好好学习‘, ‘f‘: ‘100\n‘}
从上面的事例看出,通过string转成json后,再通过json.dumps转成字符串后,原先的好好学习变成了中文编码,存储到文件中也是中文编码,很不直观。
经过摸索,采用如下方法即可使得dumps转成中文(ensure_ascii=False)
dumps_str = json.dumps(json_data, ensure_ascii=False, indent=4)dumps_strOut[30]: ‘{\n "f": "100\\n",\n "a": " 1",\n "b": "好好学习"\n}‘
时间: 2024-11-07 05:22:17