Необходимо обработать *.json в .txt
Необходимо с помощью Python написать программу, которая бы считывала файл в формате json, обрабатывала информацию и записывала ее в файл текст.
В json файле информация дана в следующем формате:
{
"userId": 1,
"id": 1,
"title": "some text one",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "some text two",
"completed": false
},
{
"userId": 1,
"id": 3,
"title": "some text three",
"completed": true
},
{
"userId": 2,
"id": 22,
"title": "distinctio vitae autem nihil ut molestias quo",
"completed": true
}
Необходимо, чтобы в файл в формате текст записывалась информация в следующем формате:
Юзер №1
Завершил задачи:
some text three
Осталось выполнить:
some text one
some text two
Мой код:
import json
import datetime
def My_mission_true(id, title):
now = datetime.datetime.now()
filename = str(id) + '_' + str(now.strftime("%Y-%m-%dT%H-%M")) + '.txt'
with open(filename.rstrip(), 'a') as l:
l.writelines(f'Юзер №{id}\n')
l.writelines(f'Осталось выполнить:\n{title}\n')
def My_mission_false(id, title):
now = datetime.datetime.now()
filename = str(id) + '_' + str(now.strftime("%Y-%m-%dT%H-%M")) + '.txt'
with open(filename.rstrip(), 'a') as l:
l.writelines(f'Юзер№{id}\n')
l.writelines(f'Завершил задачи:\n{title}\n')
with open('todos.json', 'r') as inf:
text = json.load(inf)
for line in text:
x = line.get('completed')
if x is True:
My_mission_true(line['userId'], line["title"])
elif x is False:
My_mission_false(line['userId'], line["title"])
Проблема в том, что каждая новая задача записывается в новую строку, а надо, чтобы одному юзеру записывались сразу все завершенные задачи и ниже оставшиеся задачи.
Ответы (1 шт):
Автор решения: Sergey M
→ Ссылка
import json
import datetime
def get_output(users):
now = datetime.datetime.now()
users_iter = iter(users)
for user in users_iter:
filename = str(user) + '_' + str(now.strftime("%Y-%m-%dT%H-%M")) + '.txt'
with open(filename.rstrip(), 'w') as l:
l.writelines(f'Юзер №{user}\n')
l.writelines('Осталось выполнить:\n')
l.writelines('\n'.join(users[user]['not_completed']))
l.writelines('\nЗавершил задачи:\n')
l.writelines('\n'.join(users[user]['completed']))
with open('todos.json', 'r') as inf:
text = json.load(inf)
users = {}
for line in text:
user_id = line['userId']
if user_id not in users:
users[user_id] = {
'completed': [],
'not_completed': []
}
if line.get('completed'):
users[user_id]['completed'].append(line['title'])
else:
users[user_id]['not_completed'].append(line['title'])
get_output(users)