将csv转换为json格式并使用itertool.group
按特定数据分组之后。我试图在中间插入一个新对象,以将现有数据传递给新对象。
CSV文件:
date,ref_num,description,debit,credit,coa_code,coa_name
2018-12-28,PV18/12/060,magicc,,916.60,310-1000,fineTaste
2018-12-28,PV18/12/060,youngClothes,916.60,,405-F005,magicc
代码
import csv
import json
from itertools import groupby
with open("ledgers.csv", "r") as csv_ledger:
r = csv.DictReader(csv_ledger)
data = [dict(d) for d in r]
groups = []
for k, g in groupby(data, lambda r: (r['ref_num'], r['date'])):
groups.append({
"date": k[1],
"ref_num": k[0],
"items": [{k: v for k, v in d.items() if k not in ['ref_num',
'date']} for d in list(g)]
})
print(json.dumps(groups, indent = 4))
结果
[
{
"date": "2018-12-28",
"ref_num": "PV18/12/060",
"items": [
{
"description": "magicc",
"debit": "",
"credit": "916.60",
"coa_code": "310-1000",
"coa_name": "fineTaste"
},
{
"description": "youngClothes",
"debit": "916.60",
"credit": "",
"coa_code": "405-F005",
"coa_name": "magicc"
}
]
}
]
这是当前结果,我需要在信用额下方插入info
,该对象将包含coa_code
和coa_name
。因此,我确实尝试在“项目”中添加信息,但是它不起作用。
新代码
with open("ledgers.csv", "r") as csv_ledger:
r = csv.DictReader(csv_ledger)
data = [dict(d) for d in r]
groups = []
for k, g in groupby(data, lambda r: (r['ref_num'], r['date'])):
groups.append({
"date": k[1],
"ref_num": k[0],
"items": [{k: v, 'info': {'coa_code': v}} for k, v in
d.items() if k not in ['ref_num', 'date'] for d in list(g)]
})
预期结果
[
{
"date": "2018-12-28",
"ref_num": "PV18/12/060",
"items": [
{
"description": "magicc",
"debit": "",
"credit": "916.60",
"info": {
"coa_code": "310-1000",
"coa_name": "fineTaste"
}
},
{
"description": "youngClothes",
"debit": "916.60",
"credit": "",
"info": {
"coa_code": "405-F005",
"coa_name": "magicc"
}
}
]
}
]
答案 0 :(得分:3)
Private Sub CommandButton2_Click()
Dim i As Long
For i = 0 To ListBox1.ListCount
For x = 1 To 14
Sheets("Database").Range("B2").End(xlDown).Offset(i + 1, x - 1) =
ListBox1.List(i, x - 1) 'ListBoxl.List(i, x)
Next x
Next i
End Sub
首先,我建立了import csv
import json
from itertools import groupby
with open("test.csv", "r") as csv_ledger:
r = csv.DictReader(csv_ledger)
data = [dict(d) for d in r]
groups = []
for k, g in groupby(data, lambda r: (r['ref_num'], r['date'])):
items = []
for i in g:
info = {k: v for k, v in i.items() if k in ['coa_code','coa_name']}
item = {k: v for k, v in i.items() if k not in ['ref_num',
'date', 'coa_code', 'coa_name']}
item.update({'info':info})
items.append(item)
groups.append({
"date": k[1],
"ref_num": k[0],
"items": items
})
print(json.dumps(groups, indent = 4))
,因为以后从info
中提取要困难得多,然后我制作了items
,这是item
中的每个词典,其中都包含一个{{1} }。然后,我在每个“项目”后面附加“项目”,以形成组内的项目列表。组建立后,我可以在items
列表中附加所有信息。
PS:我之所以给我的.csv info
打电话是因为我躺在那里,请小心更改名称。
干杯!