【发布时间】:2017-01-05 08:07:00
【问题描述】:
我正在尝试从 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 |
位置 = 第 1 列:ID |第 2 栏:艺术家 |第 3 栏:歌曲 |第四栏:专辑
得到这个输出:
{"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"
},
]
}
【问题讨论】:
-
仅针对问题 1,为您的 DictReader 设置使用以下 sn-p:
import collections ; reader = DictReader(csvfile, fieldnames, dict_class=collections.OrderedDict) -
2 & 3 不清楚。如果您希望其他人提供帮助,请指定预期输出。
-
导入在开头进入您的导入,
reader =行是您的 DictReader 初始化的直接替代品。 -
预期的输出是我说的第一件事
-
当我把“导入收藏;”在顶部,并添加“reader = DictReader(csv..)”它说 reader = DictReader(csvfile, dict_class=collections.OrderedDict) NameError: name 'DictReader' is not defined
标签: python arrays json csv output