简体   繁体   English

如何使用模块将Python Json输出另存为CSV文件

[英]How to save Python Json output as a CSV file using modules

I'm trying to get the data output I have, saved as an xlsm or csv file, but I don't grasp how I do that. 我正在尝试获取保存为xlsm或csv文件的数据输出,但是我不知道该怎么做。 The code include one of my attempts 该代码包括我的尝试之一

import requests
import xlsxwriter

BASE_URL = 'https://restapi.e-conomic.com/'
HEADERS = {
  'X-AgreementGrantToken': 'demo',
  'X-AppSecretToken': 'demo',
  'Content-type': 'application/json'
}
def get_invoice():
  url = "{0}/{1}".format(BASE_URL, 'invoices/booked')
  resp = requests.get(url, headers=HEADERS)
  print(resp)
  print(resp.json())
  workbook = xlsxwriter.Workbook('demo1.xlsx')
  worksheet = workbook.add_worksheet()
  worksheet.write(1, 1, resp)
  workbook.close()

if __name__ == "__main__":
  get_invoice()

Can anyone tell me, what I'm doing wrong? 谁能告诉我,我在做什么错?

* EDIT * *编辑*

Hello again guys and girls, 再次大家好,

I've gotten a little further than yesterday, by following this answer to a question 按照这个问题的答案 ,我已经比昨天走得更远

import requests
import json
import csv

BASE_URL = 'https://restapi.e-conomic.com/'
HEADERS = {
  'X-AgreementGrantToken': 'demo',
  'X-AppSecretToken': 'demo',
  'Content-type': 'application/json'
}


def get_invoice():
  url = "{0}/{1}".format(BASE_URL, 'invoices/booked')
  resp = requests.get(url, headers=HEADERS)
  whale = (resp.json)
  print(resp)
  print(whale())
  output_fil = 'blab.csv'
  horse = len(whale) - 1

  data_til_fil = open(output_fil, 'w', newline='')
  csv_writer = csv.writer(data_til_fil, delimiter=";")
  csv_writer.writerow(["bookedInvoiceNumber","date","netAmount","vatAmount","grossAmount","dueDate"])

  for i in range(0, horse):
    meetup = whale[i]
    bookedInvoiceNumber = meetup['bookedInvoiceNumber']
    date = meetup['date']
    netAmount = meetup['netAmount']
    vatAmount = meetup['vatAmount']
    grossAmount = meetup['grossAmount']
    dueDate = meetup['dueDate']
    csv_writer.writerow([bookedInvoiceNumber,date,netAmount,vatAmount,grossAmount,dueDate])
    data_til_fil.close()

if __name__ == "__main__":
  get_invoice()

I have however still trouble with getting it to work, as it doesn't like my 但是,我仍然无法使其正常工作,因为它不喜欢我的

horse = len(whale) - 1 

line. 线。 Python responds with Python回应

TypeError: object of type 'method' has no len()

Is there anyone here who are patient enough to help me with this? 这里有没有足够的耐心帮助我的人? I can say, a lot of people who uses e-conomic, would appreciate it, now and in the future. 我可以说,无论现在还是将来,许多使用电子经济学的人都会很感激。 :-) :-)

When you use worksheet.write, it only write to 1 specific cell, you wouldn't want to write every thing in a single cell, would you? 当您使用worksheet.write时,它仅写入1个特定的单元格,您不想在一个单元格中编写所有内容,对吗? Ref to https://stackoverflow.com/a/35623260/7492424 引用https://stackoverflow.com/a/35623260/7492424

Just replace 只需更换

worksheet.write(1, 1, resp)

with

json_to_excel(worksheet, resp.json())

def json_to_excel(ws, data, row=0, col=0):
    if isinstance(data, list):
        row -= 1
        for value in data:
            row = json_to_excel(ws, value, row+1, col)
    elif isinstance(data, dict):
        max_row = row
        start_row = row
        for key, value in data.iteritems():
            row = start_row
            ws.write(row, col, key)
            row = json_to_excel(ws, value, row+1, col)
            max_row = max(max_row, row)
            col += 1
        row = max_row
    else:
        ws.write(row, col, data)

    return row

There are a couple of issues with your new code. 您的新代码有几个问题。

  1. resp.json is a method, so you need to call it to get the values (resp.json()). resp.json是一种方法,因此您需要调用它来获取值(resp.json())。 And the result is a map, I suppose you need to 'collection' to extract the content. 结果是一张地图,我想您需要“收集”以提取内容。

    In [17]: resp.json().keys() Out[17]: dict_keys(['collection', 'metaData', 'pagination', 'self']) 在[17]中:resp.json()。keys()在[17]中:dict_keys(['collection','metaData','pagination','self'])

  2. You closed the file too early, please move the close out of the for loop. 您关闭文件的时间过早,请将关闭操作移出for循环。

Please try below code and see whether that's what you wanted. 请尝试下面的代码,看看是否正是您想要的。

import requests
import json
import csv

BASE_URL = 'https://restapi.e-conomic.com/'
HEADERS = {
  'X-AgreementGrantToken': 'demo',
  'X-AppSecretToken': 'demo',
  'Content-type': 'application/json'
}


def get_invoice():
    url = "{0}/{1}".format(BASE_URL, 'invoices/booked')
    resp = requests.get(url, headers=HEADERS)
    # whale = (resp.json)
    whales = resp.json()['collection']
    #print(resp)
    #print(whale())
    output_fil = 'blab.csv'
    horse = len(whales)

    data_til_fil = open(output_fil, 'w', newline='')
    csv_writer = csv.writer(data_til_fil, delimiter=";")
    csv_writer.writerow(["bookedInvoiceNumber","date","netAmount","vatAmount","grossAmount","dueDate"])

    #for i in range(0, horse):
    for meetup in whales:
        #meetup = whale[i]
        bookedInvoiceNumber = meetup['bookedInvoiceNumber']
        date = meetup['date']
        netAmount = meetup['netAmount']
        vatAmount = meetup['vatAmount']
        grossAmount = meetup['grossAmount']
        dueDate = meetup['dueDate']
        csv_writer.writerow([bookedInvoiceNumber,date,netAmount,vatAmount,grossAmount,dueDate])
    # you closed this file too early, pleaes make sure move this out of the for loop
    data_til_fil.close()

if __name__ == "__main__":
  get_invoice()

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

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