我正嘗試使用python從CSV創建JSON。我遇到的這個問題是從數據中分離標題的方法。我當前的代碼是:Python將CSV轉換爲帶有標頭的JSON
import csv
import json
with open('input.csv') as f:
columns = ("Column 1", "Column 2")
reader = csv.DictReader(f, columns)
rows = list(reader)
with open('output.json', 'w') as f:
json.dump(rows, f, indent=4)
但這返回
[
{
"Column 2": null,
"Column 1": "Title"
},
{
"Column 2": " data2",
"Column 1": "data1"
},
{
"Column 2": " data4",
"Column 1": "data3"
},
{
"Column 2": " data6",
"Column 1": "data5"
}
]
,而不是
[
"Title1": {
{
"Column 2": " data2",
"Column 1": "data1"
},
{
"Column 2": " data4",
"Column 1": "data3"
},
{
"Column 2": " data6",
"Column 1": "data5"
}
}
]
繼承人的CSV會是什麼樣子供參考的例子:
Title
data1, data2
data3, data4
data5, data6
Title2
data1, data2
data3, data4
data5, data6
你需要明確地建立另一種數據結構。一個字典讀者可能無法幫助你。 –
你的例子不太可能。你把「Tittle1」作爲沒有鍵的字典的關鍵字。 – dawg