简体   繁体   English

如何将api output json转换为csv文件

[英]how to convert api output json to csv file

i have a api output as follows我有一个 api output 如下

{
 "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"
    }
]
}

i need to save it as create and save it as a csv file我需要将其保存为创建并将其保存为 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}

when executing this end point i am getting the following error list' object has no attribute 'read'执行此终点时,我收到以下错误列表'object 没有属性'read'

Kindly guide请指导

write a separate function and call it after the dictionary values写一个单独的 function 并在字典值之后调用它

    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']])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM