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

时间:2018-02-11 21:46:09

标签: python json excel csv python-requests

我试图获取我拥有的数据输出,保存为xlsm或csv文件,但我不知道我是如何做到这一点的。 代码包括我的一次尝试

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()

谁能告诉我,我做错了什么?

*编辑*

你好男女老少,

我比昨天更进一步,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()
然而,我仍然无法让它发挥作用,因为它不喜欢我的

horse = len(whale) - 1 

线。 Python以

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

这里有没有人有耐心帮我这个?我可以说,很多使用e-conomic的人,现在和将来都会欣赏它。 :-)

2 个答案:

答案 0 :(得分:1)

当你使用worksheet.write时,它只会写入1个特定的单元格,你不想写一个单元格中的每一个东西,对吗? 参考https://stackoverflow.com/a/35623260/7492424

只需替换

worksheet.write(1, 1, resp)

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

答案 1 :(得分:0)

您的新代码存在一些问题。

  1. resp.json是一个方法,所以你需要调用它来获取值(resp.json())。结果是一张地图,我想你需要收集'提取内容。

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

    < / LI>
  2. 您过早关闭了文件,请将结束移出for循环。

  3. 请尝试下面的代码,看看这是否是你想要的。

    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()