关于Python dict存中文字符dumps()的问题
background
之前数据库只区分了android,ios两个平台,游戏上线后现在pm想要区分国服,海外服,港台服。这几个字段从前端那里的接口获得,code过程中发现无论如何把中文的value丢到dict中存到数据库中就变成类似这样**"\u56fd\u670d"**
solution
1.首先怀疑数据库编码问题,但看了一下数据库其他字段有中文格式的,所以要先check数据库(mysql)的字符编码。
可以看到明明就tmd是utf-8啊,所以一定不是数据库层出现的问题,回到代码debug
2.google一下
这个问题好多都是python2的解决方案,找到了一个感觉靠谱点的
dict1 = {'name':'张三'} print(json.dumps(dict1,encoding='utf-8',ensure_ascii=false))
博客中的解法,但是我的python版本是3.9,就会报error如下
exception in thread thread-1: traceback (most recent call last): file "/usr/local/python3/lib/python3.9/threading.py", line 950, in _bootstrap_inner self.run() file "/usr/local/python3/lib/python3.9/threading.py", line 888, in run self._target(*self._args, **self._kwargs) file "/home/dapan_ext/project_table.py", line 91, in http_request self.get_data(project_response_data) file "/home/dapan_ext/project_table.py", line 115, in get_data json.dumps(dict_1, encoding='utf-8', ensure_ascii=false) file "/usr/local/python3/lib/python3.9/json/__init__.py", line 234, in dumps return cls( typeerror: __init__() got an unexpected keyword argument 'encoding'
意思就是:在__init__json这个东东的时候它不认识'encoding'这个argument。
那就翻阅源码康康->->:
def dumps(obj, *, skipkeys=false, ensure_ascii=true, check_circular=true, allow_nan=true, cls=none, indent=none, separators=none, default=none, sort_keys=false, **kw): """serialize ``obj`` to a json formatted ``str``. if ``skipkeys`` is true then ``dict`` keys that are not basic types (``str``, ``int``, ``float``, ``bool``, ``none``) will be skipped instead of raising a ``typeerror``. if ``ensure_ascii`` is false, then the return value can contain non-ascii characters if they appear in strings contained in ``obj``. otherwise, all such characters are escaped in json strings. if ``check_circular`` is false, then the circular reference check for container types will be skipped and a circular reference will result in an ``overflowerror`` (or worse). if ``allow_nan`` is false, then it will be a ``valueerror`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the json specification, instead of using the javascript equivalents (``nan``, ``infinity``, ``-infinity``). if ``indent`` is a non-negative integer, then json array elements and object members will be pretty-printed with that indent level. an indent level of 0 will only insert newlines. ``none`` is the most compact representation. if specified, ``separators`` should be an ``(item_separator, key_separator)`` tuple. the default is ``(', ', ': ')`` if *indent* is ``none`` and ``(',', ': ')`` otherwise. to get the most compact json representation, you should specify ``(',', ':')`` to eliminate whitespace. ``default(obj)`` is a function that should return a serializable version of obj or raise typeerror. the default simply raises typeerror. if *sort_keys* is true (default: ``false``), then the output of dictionaries will be sorted by key. to use a custom ``jsonencoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg; otherwise ``jsonencoder`` is used. """ # cached encoder if (not skipkeys and ensure_ascii and check_circular and allow_nan and cls is none and indent is none and separators is none and default is none and not sort_keys and not kw): return _default_encoder.encode(obj) if cls is none: cls = jsonencoder return cls( skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, default=default, sort_keys=sort_keys, **kw).encode(obj)
注意到这里:
if ``ensure_ascii`` is false, then the return value can contain non-ascii
characters if they appear in strings contained in ``obj``. otherwise, all
such characters are escaped in json strings.
意思就是:
ensure_ascii置为false时,返回值就可以返回非ascii编码的字符,这岂不正是我们需要的,got it!
回去改代码:
server_name = str(related['name']) # print(server_name) dict_1 = {'appkey': related['appkey'], 'client': related['client'], 'name': server_name} crasheye.append(dict_1) crasheyes = json.dumps(crasheye, ensure_ascii=false)
完美解决问题(●ˇ∀ˇ●)
到此这篇关于python dict存中文字符dumps()的文章就介绍到这了,更多相关python dict中文字符dumps()内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: MySQL的字符编码体系(二)数据传输编码_MySQL
下一篇: stl中的size的坑
推荐阅读
-
python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换)
-
解决Python3中的中文字符编码的问题
-
python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换)
-
解决python写入带有中文的字符到文件错误的问题
-
浅谈python下含中文字符串正则表达式的编码问题
-
在Python中关于中文编码问题的处理建议
-
关于Python中的字符集的问题讲解
-
关于python中文编码乱码问题的两篇文章汇总
-
浅谈python str.format与制表符 关于中文对齐的细节问题
-
关于Python dict存中文字符dumps()的问题