我想在Python中將CSV轉換爲JSON。我能夠將簡單的csv文件轉換爲json,但無法將兩個csv連接到一個嵌套的json中。Python:將兩個CSV添加到一個嵌套的JSON Python
emp.csv:
empid | empname | empemail
e123 | adam | [email protected]
e124 | steve | [email protected]
e125 | brian | [email protected]
e126 | mark | [email protected]
items.csv:
empid | itemid | itemname | itemqty
e123 | itm128 | glass | 25
e124 | itm130 | bowl | 15
e123 | itm116 | book | 50
e126 | itm118 | plate | 10
e126 | itm128 | glass | 15
e125 | itm132 | pen | 10
輸出應該是這樣的:
[{ "empid": "e123", "empname": "adam", "empemail": "[email protected]", "items": [{ "itemid": "itm128", "itmname": "glass", "itemqty": 25 }, { "itemid": "itm116", "itmname": "book", "itemqty": 50 }] }, and similar for others]
,我寫的代碼:
import csv import json empcsvfile = open('emp.csv', 'r') jsonfile = open('datamodel.json', 'w') itemcsvfile = open('items.csv', 'r') empfieldnames = ("empid","name","phone","email") itemfieldnames = ("empid","itemid","itemname","itemdesc","itemqty") empreader = csv.DictReader(empcsvfile, empfieldnames) itemreader = csv.DictReader(itemcsvfile, itemfieldnames) output=[]; empcount=0 for emprow in empreader: output.append(emprow) for itemrow in itemreader: if(itemrow["empid"]==emprow["empid"]): output.append(itemrow) empcount = empcount +1 print output json.dump(output, jsonfile,sort_keys=True)
,它亙古不變的工作。 需要幫助。謝謝
是CSV文件 - 逗號分隔或管道分隔? – Rocky
我運行了你的代碼,並提出了一些打印語句,這是什麼輸出 - {'empid':'empid | empname | empemail','phone':None,'name':None,'email':None} {'empid':'e123 | adam | [email protected]','phone':None,'name':None,'email':None} {'empid':'e124 |史蒂夫| [email protected]','phone':None,'name':None,'email':None} {'empid':'e125 |布萊恩| [email protected]','phone':None,'name':None,'email':None} {'empid':'e126 | mark | [email protected]','phone':None,'name':None,'email':None} 所以,正如你看到的那樣,因爲它是管道分離的,所以整行被認爲是empid – Rocky
感謝你的提問。 – Kevin