Запись в JSON с отступами в Python

Вот несколько методов Python для записи в JSON с отступами:

Метод 1. Использование модуля json

import json
data = {'key1': 'value1', 'key2': 'value2'}
# Writing to JSON file with indentation
with open('output.json', 'w') as file:
    json.dump(data, file, indent=4)

Метод 2: использование функции dumpс параметром indent

import json
data = {'key1': 'value1', 'key2': 'value2'}
# Writing to JSON file with indentation
with open('output.json', 'w') as file:
    json.dump(data, file, indent=4)

Метод 3: использование функции dumpс json.dumpsи параметром indent

import json
data = {'key1': 'value1', 'key2': 'value2'}
# Convert data to JSON string with indentation
json_str = json.dumps(data, indent=4)
# Writing JSON string to file
with open('output.json', 'w') as file:
    file.write(json_str)

Метод 4. Использование json.dumpс параметрами defaultи indent

import json
data = {'key1': 'value1', 'key2': 'value2'}
# Writing to JSON file with indentation
with open('output.json', 'w') as file:
    json.dump(data, file, default=str, indent=4)

Метод 5: использование модуля pprint

import pprint
data = {'key1': 'value1', 'key2': 'value2'}
# Writing to JSON file with indentation
with open('output.json', 'w') as file:
    pprint.pprint(data, file)