json.dumps красиво распечатать в Python

Содержание
Introduction
Спецификация
JSON
Словарь
json.dumps + json.loads
Вложенные объекты
Статьи про Python

Introduction

Если нужно вывести в консоль словарь или json это можно сделать с помощью json.dumps

Спецификация json.dumps

Если вы хотите сразу же изучить полученный json можно воспользоваться методом dumps()

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 using this conversion table. The arguments have the same meaning as in dump(). Note Keys in key/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, loads(dumps(x)) != x if x has non-string keys.

JSON

Если нужно распечатать JSON

import json print(json.dumps(response.json(), indent=4))

Словарь

Если нужно распечатать не JSON а словарь, json.dumps нужно использовать так:

import json print(json.dumps(resp.dict, indent=4)) # Если нужно отсортировать словарь print(json.dumps(resp.dict, indent=4, sort_keys=True))

json.dumps + json.loads

Часто приходится использовать связку json.dumps + json.loads

import json response_json = json.loads(response.text) print(json.dumps(response_json, indent=4))

Обратиться ко вложенному объекту

Предположим, приходит следующий json

{ "address": { "version": 1, "date": "2021-Aug-11", "cities": [ { "id": "0", "name": "malaga", "place": { "id": "100", "name": "Форт", "status": "VISITED" } }, { "id": "1", "name": "benalmadena", "place": { "id": "150", "name": "Парк Палома", "status": "VISITED" } } ] } }

Из него нам интересен только статус городов: посещён или не посещён.

Нужно обратиться ко вложенным в json объектам

import json data_set = { "address": { "version": 1, "date": "2026-Oct-17", "cities": [ { "id": "0", "name": "malaga", "place": { "id": "100", "name": "Форт", "status": "VISITED" } }, { "id": "1", "name": "benalmadena", "place": { "id": "150", "name": "Парк Палома", "status": "VISITED" } } ] } } json_dump = json.dumps(data_set) response_json = json.loads(json_dump) cities = response_json["address"]["cities"] for city in cities: print(city["place"]["status"])

VISITED
VISITED

Article author: Andrei Olegovich

Похожие статьи
Interactive mode
str: strings
\: long line wrapping
Lists []
if, elif, else
Loops
Methods
Functions
*args **kwargs
enum
Get Variable Type
Testing with Python
Calling REST API with Python
Files: write, read, append, context manager…
Download File
SQLite3: database
datetime: Date and Time в Python
json.dumps
Selenium + Python
Issues with Python
DJANGO
Flask
ZPL printer script
socket :Python Sockets
Virtual Environment
subprocess: shell commands execution
multiprocessing
psutil: system usage
sys.argv: command prompt variables
PyCharm: IDE
pydantic: data validation
paramiko: SSH with Python
enumerate

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: