您好,登錄后才能下訂單哦!
本篇內容主要講解“怎么解決關于Python dict存中文字符dumps()的問題”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“怎么解決關于Python dict存中文字符dumps()的問題”吧!
之前數據庫只區(qū)分了Android,IOS兩個平臺,游戲上線后現在PM想要區(qū)分國服,海外服,港臺服。這幾個字段從前端那里的接口獲得,code過程中發(fā)現無論如何把中文的value丟到dict中存到數據庫中就變成類似這樣**"\u56fd\u670d"**
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()的問題”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。