Для синтаксического анализа файла используйте json.load():
withopen('filename.txt', 'r') as handle: parsed = json.load(handle)
Ответ 2
Вы можете сделать это в командной строке:
python3 -m json.tool some.json
(как уже упоминалось в комментариях к вопросу, спасибо @Kai Petzke за предложение python3).
На самом деле python не мой любимый инструмент в том, что касается обработки json в командной строке. Для простой красивой печати все в порядке, но если вы хотите манипулировать json, это может стать чрезмерно сложным. Вскоре вам понадобится написать отдельный файл скрипта, в результате вы могли бы получить карты, ключами которых являются u "some-key" (python unicode), что затрудняет выбор полей и на самом деле не способствует красивой печати.
и вы получаете цвета в качестве бонуса (и намного более легкую расширяемость).
Дополнение: В комментариях есть некоторая путаница по поводу использования jq для обработки больших JSON-файлов, с одной стороны, и наличия очень большой jq-программы, с другой. Для красивой печати файла, состоящего из одного большого объекта JSON, практическим ограничением является оперативная память. Для pretty-печати файла объемом 2 ГБ, состоящего из одного массива реальных данных, "максимальный размер резидентного набора", необходимый для pretty-печати, составлял 5 ГБ (независимо от того, используется jq 1.5 или 1.6). Обратите также внимание, что jq можно использовать из python после pip install jq.
Ответ 3
After reading the data with the json standard library module, use the pprint standard library module to display the parsed data. Example:
import json import pprint
json_data = None withopen('file_name.txt', 'r') as f: data = f.read() json_data = json.loads(data)
# print json to screen with human-friendly formatting pprint.pprint(json_data, compact=True)
# write json to file with human-friendly formatting pretty_json_str = pprint.pformat(json_data, compact=True).replace("'",'"')
withopen('file_name.json', 'w') as f: f.write(pretty_json_str)
The default indent is 1, so you may want to specify your own.
Note that you can specify where it will wrap with the width argument.
It is necessary to replace 'single quotes' with 'double quotes' in the string returned by pprint.pformat(), because single quotes are not valid json. When you look at the file in your text editor, it may be unable to highlight the json properly.
In any case, you may want to save it as valid json, so that you can as a human can simply read your json files comfortably, if it is not more important that they are formatted without spacing so they can be computer-processed with blinding speed.