Python форматирование моего вывода JSON
# -*- coding: utf-8 -*-
import json
from pprint import pprint
drink_list = [23,601,633,673,607,662,6622,6014,6104,615,038,606,607,627,6094]
filename = (r'C:\Users\desktop\pizza\123template.json')
with open(filename, 'r') as f:
data = f.read()
try:
template = json.loads(data)
except Exception:
# this file can also be here
print('json exception')
raise
for output in drink_list:
print(output)
temp = template.copy()
temp["meta"]["sodanumber"] = output
with open(r'C:\Users\desktop\pizza\123\{}.json'.format(output, indent=40), 'w', encoding='cp1252') as f:
data = json.dumps(temp)
f.write(data)
# pprint.pprint(temp, width=60)
IndentationError: unindent не соответствует ни одному внешнему уровню отступа.
Но я думаю, что это больше, чем простой абзац. Я могу заставить свою консоль изменить форматирование, но нужно изменить форматирование в реальном выходном файле. Но где бы я добавил свое дополнительное форматирование в строку "с открытым"?
Прочитали материал по этому 4 часа и простые примеры, но выполняет ли pprint большую часть работы?
Текущий вывод - это тонны рабочего текста. Вывод должен выглядеть как показано ниже. Как я могу сделать так, чтобы это выглядело так:
{
"meta": {
"drinkNumber": 662,
"effectiveDate": "2016-10-12 16:00:31",
"documentType": "checkout-device"
},
"documents": [
{
"code": "Checkout2",
"name": "Printer 2",
"port": "COM2",
"type": "LABEL",
Токовый выход:
{ "meta": { "drinkNumber": 662, "effectiveDate": "2016-10-12 16:00:31", "documentType": "checkout-device" },"documents": [{
"code": "Checkout2","name": "Printer 2","port": "COM2","type": "LABEL",
1 ответ
import json
data = { "meta": { "drinkNumber": 662, "effectiveDate": "2016-10-12 16:00:31", "documentType": "checkout-device" },"documents": [{ "code": "Checkout2","name": "Printer 2","port": "COM2","type": "LABEL"}]}
json.dumps(data, sort_keys=True, indent=4)
Выход:
{
"documents": [
{
"code": "Checkout2",
"name": "Printer 2",
"port": "COM2",
"type": "LABEL"
}
],
"meta": {
"documentType": "checkout-device",
"drinkNumber": 662,
"effectiveDate": "2016-10-12 16:00:31"
}
}
Примечание: ваш текущий вывод не завершен.