关于Python dict存中文字符dumps()的问题
作者:Loganer 发布时间:2022-08-22 17:53:17
标签: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)
完美解决问题(●ˇ∀ˇ●)
来源:https://blog.csdn.net/wyh1618/article/details/121013434
0
投稿
猜你喜欢
- 1、说明tqdm是一个方便且易于扩展的Python进度条,可以在python执行长循环时在命令行界面实时地显示一个进度提示信息,包括执行进度
- 不知道从什么时候开始,在网络上到处可以看到div+css,到底什么是div+css呢?难道就是传说中的标准重构吗?标准从最简单的根源来说不是
- 生成HTML方法主要步骤只有两个:一、获取要生成的html文件的内容二、将获取的html文件内容保存为html文件我在这里主要说明的只是第一
- 函数初解function,是一种语法结构,将实现某一个功能的代码块(多行代码)封装到一个结构中实现代码的重复利用函数定义语法:关键点:fun
- 一、分屏展示当你想同时看到多个文件的时候:右击标签页;选择 move right 或者 split vertical;效果:二、远程 Pyt
- Django 分页功能的实现,供大家参考,具体内容如下创建项目创建APP,添加APP这些就不在多说我们这次重点来看到视图函数下面是路由设置视
- 说来惭愧,以前在去掉数组的空值是都是强写foreach或者while的,利用这两个语法结构来删除数组中的空元素,简单代码如下:<?ph
- 1、遇到的问题:numpy版本im_data = dataset.ReadAsArray(0,0,im_width,im_height)#获
- 现在大家都在讨论Web2.0 ,大家都在搞用户行为前端设计,现在注册一个ID一般只需要几秒钟,站长期望其产生高价值的UGC,形成一个只需要审
- 网上广泛流传的取 object 的绝对位置的做法是:var getAbsPos = function(pTar
- 导读我们在使用selenium打开google浏览器的时候,默认打开的是一个新的浏览器窗口,而且里面不带有任何的浏览器缓存信息。当我们想要爬
- 天极网软件频道的图片切换特效,完全是由XHTML+CSS+JS实现的图片切换特效,弄了好半天啊!!如果您使用或者转载请别忘了加我的一个连接啊
- 本文实例讲述了微信小程序实现图片上传、删除和预览功能的方法。分享给大家供大家参考,具体如下:这里主要介绍一下微信小程序的图片上传图片删除和图
- 什么是JSON http://www.json.org/json-zh.htmlJSON(Javascript Object Notatio
- 使用MySQL的命令终端时,如果输入SQL有误,将有beep声。若要关闭该功能,根据mysql --help,使用mysql --no-be
- 脚本内容代码如下:from mitmproxy import http, ctxfrom multiprocessing import Lo
- 初识项目打开VS2015,创建Web项目,选择ASP.NET Web Application,在弹出的窗口里选择ASP.NET 5 Webs
- 我们在用python进行程序开发的时候,很多时候我们需要检测一下当前的变量的数据类型。比如需要在使用字符串操作函数之前先检测一下当前变量是否
- 一个很不错的效果,用键盘的箭头键控制一个漂亮的箭头!也许能给你启发,做出一款有趣的小游戏呢!运行代码框<html xmlns:v=&q
- 如何用JMail同时给多人发信?在ASP中,为什么我在Jmail收件人处指定多个收件人时,像这样:JMail.AddRecipient&nb