关于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


猜你喜欢
- 开通了一个阿里云来玩,记录一下环境搭建的过程运行环境ECS Ubuntu 16.04 64位过程#切换到安装文件夹cd /usr/local
- 一、网络请求在uni中可以调用uni.request方法进行请求网络请求需要注意的是:在小程序中网络相关的 API 在使用前需要配置域名白名
- 首先我们需要几个包:requests, lxml, bs4, pymongo, redis1. 创建爬虫对象,具有的几个行为:抓取页面,解析
- 问题:在论坛发表回复时出现“The table is full”的提示,字面意义上是数据表已满的意思。因为很少有开发者遭遇单一表超过4G的情
- 本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理。以下文章来源于早起Python ,作者投
- Pytorch调用forward()函数Module类是nn模块里提供的一个模型构造类,是所有神经网络模块的基类,我们可以继承它来定义我们想
- 前言用阻塞 API 写同步代码最简单,但一个线程同一时间只能处理一个请求,有限的线程数导致无法实现万级别的并发连接,过多的线程切换也抢走了
- python 判断三个数字中的最大值,具体代码如下所示:#判断三个数中最大值n1= int(input('please enter
- 废话不多说了直接给大家介绍canvas实现手机端用来上传用户头像的代码,具体代码如下所示:<!DOCTYPE html><
- (1)IN运算符:它可以用来匹配一个固定集合中的某一项。比如说一个集合里面的年份有(2001,2003,2005),那么就可以有:SELEC
- 输入半径,计算圆的周长、面积、球体体积,并画出这个圆。拖动条、输入框和图像控件的数据保持一致!Fedora下测试通过#https://git
- 在php.ini中存在三项配置项:session.save_path="" --设置session的存储路径
- 本文实例讲述了django框架模板语言使用方法。分享给大家供大家参考,具体如下:模板功能作用:生成html界面内容,模版致力于界面如何显示,
- 本篇文章起源于在GCR MVP Open Day的时候和C# MVP张响讨论连接池的概念而来的。因此单独写一篇文章剖析一下连接池。 为什么需
- 事务特性1、原子性(Atomicity):事务开始后所有操作,要么全部做完,要么全部不做,不可能停滞在中间环节。2、一致性(Consiste
- SQL Server 2008“阻止保存要求重新创建表的更改”的错误的解决方案是本文我们主要要介绍的内容,情况是这样的:我们在用SQL Se
- 在pycharm中,当调用( import / from … import… )其他文件夹下的函数或模块,会发现编辑器无法识别( can n
- 先给大家介绍下python制作定时发送信息脚本,内容如下所示:文章中提到的菜单是右下角这个需求我们需要做到打开微信获取输入框焦点及输入思路1
- 今天接到一任务,有一张学生信息表(Excel表),里面有一万多条记录,现在要把这张表导入到数据库中,并设置学生学号为主键,但是现在这张表中的
- 最近在做一个项目,用双通道神经网络,每个通道输入不同数据训练,具有相同label。开始没想到如何实现,网上很多例子都是单通道,即便找到双通道