weranda
@weranda

Как сохранить JSON с кириллицей, чтобы она читалась?

Приветствую.
Есть словарь и его надо конвертировать в JSON так, чтобы он был читаемым. Делаю так:
nmbrs = 
{
    "one": "Один",
    "two": "Два",
    "three": "Три",
    "four": "Четыре"
}

print(json.dumps(nmbrs))

# получается вот это
# {"one": "\u041e\u0434\u0438\u043d", "two": "\u0414\u0432\u0430", "three": "\u0422\u0440\u0438", "four": "\u0427\u0435\u0442\u044b\u0440\u0435"}

Как сделать JSON читаемым в этом случае?
  • Вопрос задан
  • 1998 просмотров
Решения вопроса 3
aRegius
@aRegius
Python Enthusiast
Пропишите параметр ensure_ascii равным False:
.dumps(nmbrs, ensure_ascii=False)
Ответ написан
Комментировать
sergey-gornostaev
@sergey-gornostaev Куратор тега Python
Седой и строгий
Комментировать
trapwalker
@trapwalker Куратор тега Python
Программист, энтузиаст
Почитайте спецификацию. Если вы не научитесь этим пользоваться, то не сможете программировать.

Help on function dumps in module json:

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.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы