我试图从CSV中获取数据,并将其以JSON格式放入顶层数组。
目前我正在运行以下代码:
import csv
import json
csvfile = open('music.csv', 'r')
jsonfile = open('file.json', 'w')
fieldnames = ("ID","Artist","Song", "Artist")
reader = csv.DictReader( csvfile, fieldnames)
for row in reader:
json.dump(row, jsonfile)
jsonfile.write('\n')
CSV文件的格式如下所示:
| 1 | Empire of the Sun | We Are The People | Walking on a Dream |
| 2 | M83 | Steve McQueen | Hurry Up We're Dreaming |
Where = 列1:ID | 列2:艺术家 | 列3:歌曲 | 列4:专辑
And getting this output:
并获得以下输出:
{"Song": "Empire of the Sun", "ID": "1", "Artist": "Walking on a Dream"}
{"Song": "M83", "ID": "2", "Artist": "Hurry Up We're Dreaming"}
我正在尝试让它看起来像这样:
但我希望它更加美观易懂:
{
"Music": [
{
"id": 1,
"Artist": "Empire of the Sun",
"Name": "We are the People",
"Album": "Walking on a Dream"
},
{
"id": 2,
"Artist": "M83",
"Name": "Steve McQueen",
"Album": "Hurry Up We're Dreaming"
},
]
}
`import collections ; reader = DictReader(csvfile, fieldnames, dict_class=collections.OrderedDict)`
- Michel Müllerreader =
这一行则可以直接替换你原本使用的 DictReader 初始化。 - Michel Müller(“ID”,“Artist”,“Song”,“Artist”)
。 - chthonicdaemon