как преобразовать выходные данные api json в файл csv

#api #rest

#API #rest

Вопрос:

у меня есть вывод api следующим образом

 {
 "sub_start_date_end_date": [
    {
        "account_id": "10996fd6-a708-4d70-b65e-50620d8fbbdf",
        "country": "'USA'",
        "end_date": "Fri, 03 Sep 2021 00:00:00 GMT",
        "start_date": "Thu, 03 Sep 2020 00:00:00 GMT"
    }
]
}
  

мне нужно сохранить его как create и сохранить как csv-файл

 @final.route('/start_date-end_datess', methods=['GET'])
def subscription_datess():
subscription_id = request.args.get('subscription_id')
email = request.args.get('email')
update_query = '''
         some query            '''
result = db.session.execute(text(update_query), {'a':email})
final = [dict(i) for i in result]
excel = json.load(final)
files = csv.writer(open("test.csv", "wb "))
files.writerow(["account_id", "country", "end_date", "start_date"])
for excel in excel:
    files.writerow([excel["account_id"],
                    excel["country"],
                    excel["end_date"],
                    excel["start_date"]])
return{"sub_start_date_end_date":final}
  

при выполнении этой конечной точки я получаю следующий
список ошибок «объект не имеет атрибута «чтение»

Любезное руководство

Ответ №1:

напишите отдельную функцию и вызывайте ее после значений словаря

     final.route('/start_date-end_datess', methods=['GET'])
def subscription_datess():
    subscription_id = request.args.get('subscription_id')
    email = request.args.get('email')
    update_query = '''
             
            '''
    result = db.session.execute(text(update_query), {'a':email})
    final = [dict(i) for i in result]
    for items in final:
        write_csv(items)
    return{"sub_start_date_end_date":final}

def write_csv(data):
    with open('excel.csv', 'a') as file:
        writer = csv.writer(file)
        writer.writerow([data['account_id'],
                         data['country'],
                         data['end_date'],
                         data['start_date']])