我尝试从CSV解析名称并将它们转换为JS数组,这是我第一次尝试使用python而我无法获得JSON文件的正确结构。我的代码在下面是当前和所需的输出,任何指针都将非常感激。
import csv, json
csvPath = "forbes_pub_top_2000.csv"
jsonPath = "pub.json"
# Read CSV, filter Names, add to data
data = {}
with open(csvPath, 'r') as csv_file:
csv_reader = csv.reader(csv_file)
next(csv_reader)
for line in csv_reader:
company = line[2]
data[company] = line[2]
# Add data to root node
root = {}
root["names"] = data
# Write data to JSON file
with open(jsonPath, 'w') as json_file:
json_file.write(json.dumps(root, indent=4))
当前输出:
{
"names": {
"ICBC": "ICBC",
"China Construction Bank": "China Construction Bank",
"Berkshire Hathaway": "Berkshire Hathaway",
"JPMorgan Chase": "JPMorgan Chase",
"Wells Fargo": "Wells Fargo",
"Agricultural Bank of China": "Agricultural Bank of China",
"Bank of America": "Bank of America",
"Bank of China": "Bank of China",
...
}
期望的输出:
{
"names": ["ICBC", "China Construction Bank", "Berkshire Hathaway", "JPMorgan Chase", "Wells Fargo", "Agricultural Bank of China", "Bank of America", "Bank of China", ... ]
}
答案 0 :(得分:1)
而不是:
for line in csv_reader:
company = line[2]
data[company] = line[2]
这样做:
for line in csv_reader:
data.append(line[2])
您还需要将data
列为一个列表,而不是dict:
data = []