Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem of saving Chinese characters dumps () in Python dict

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to solve the problem of saving Chinese characters dumps () in Python dict". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to solve the problem of saving Chinese characters dumps () in Python dict".

Background

Before, the database only distinguished the two platforms of Android,IOS, but now PM wants to distinguish between national service, overseas service and Hong Kong Taiwan service after the game is launched. These fields are obtained from the interface at the front end. During the code process, it is found that no matter how to throw the Chinese value into the dict and store it in the database, it becomes something like * * "\ u56fd\ u670d" * *.

Solution

1. First of all, I suspect the problem of database coding, but take a look at the other fields of the database in Chinese format, so we should first check the character encoding of the database (MySQL).

You can see that TMD is utf-8, so it must not be the problem in the database layer. Go back to the code debug.

2.Google for a moment

Many of the solutions to this problem are Python2 solutions, and we have found one that feels more spectral.

Dict1 = {'name':' Zhang San'} print (json.dumps (dict1,encoding='utf-8',ensure_ascii=False))

The solution in the blog, but my Python version is 3.9, it will be reported to Error as follows

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'

It means: it doesn't recognize the argument of 'encoding'' in the case of _ _ init__json.

Then read the source code Kangkang->->:

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 ``room``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_ room``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 ``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, ``aggregators``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)

Notice here:

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.

It means:

When ensure_ascii is set to false, the return value can return non-ASCII encoded characters, which is exactly what we need, Got it!

Go back and change the code:

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)

● "∀" ●

At this point, I believe you have a deeper understanding of "how to solve the problem of saving Chinese characters dumps () in Python dict". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report