将 JSON 转换为 CSV 并保持列顺序
Convert JSON to CSV and maintain column order
我需要将 json 转换为 csv 以获取没有 headers 的库存 Feed,转换没有问题,但列顺序正在更改。有没有办法保持列顺序?这是我拥有的:
acmeInventory = Stock.objects.filter(product__type__in=(1, 9), status=1,
product__acmesells=True)
data=[]
for item in acmeInventory:
sku = item.product.sku
if sku == 'PROVTi-BK':
sku = 'VTi-BK'
if sku == 'PROVT-BK':
sku = 'VT-BK'
quantity = int(item.stock)
if quantity < 50:
quantity = 0
itemDict={
'Manufacturers Item #':sku,
'Quantity Available': str(quantity),
'Stocking Unit of Measure': 'EA',
'Date Available': str(today),
'Item Description': item.product.name,
}
data.append(itemDict)
print(data)
keys = data[0].keys()
with open('AcmeIAV220.csv','w', newline='') as output_file:
dict_writer = csv.DictWriter(output_file,keys)
dict_writer.writerows(data)
ftp = ftplib.FTP(host,user,password)
ftp.encoding = "utf-8"
with open('AcmeIAV220.csv', "rb") as file:
ftp.storbinary("STOR AcmeIAV220.csv", file)
ftp.dir()
尝试使用 OrderedDict 而不是 dict
我需要将 json 转换为 csv 以获取没有 headers 的库存 Feed,转换没有问题,但列顺序正在更改。有没有办法保持列顺序?这是我拥有的:
acmeInventory = Stock.objects.filter(product__type__in=(1, 9), status=1,
product__acmesells=True)
data=[]
for item in acmeInventory:
sku = item.product.sku
if sku == 'PROVTi-BK':
sku = 'VTi-BK'
if sku == 'PROVT-BK':
sku = 'VT-BK'
quantity = int(item.stock)
if quantity < 50:
quantity = 0
itemDict={
'Manufacturers Item #':sku,
'Quantity Available': str(quantity),
'Stocking Unit of Measure': 'EA',
'Date Available': str(today),
'Item Description': item.product.name,
}
data.append(itemDict)
print(data)
keys = data[0].keys()
with open('AcmeIAV220.csv','w', newline='') as output_file:
dict_writer = csv.DictWriter(output_file,keys)
dict_writer.writerows(data)
ftp = ftplib.FTP(host,user,password)
ftp.encoding = "utf-8"
with open('AcmeIAV220.csv', "rb") as file:
ftp.storbinary("STOR AcmeIAV220.csv", file)
ftp.dir()
尝试使用 OrderedDict 而不是 dict