首页 > 解决方案 > 将 Python 字符串转换为 JS 数组

问题描述

我试图从 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", ... ]
}

标签: pythonjsoncsv

解决方案


而不是这个:

for line in csv_reader:
    company = line[2]
    data[company] = line[2]

做这个:

for line in csv_reader:
    data.append(line[2])

您还需要data列出一个列表,而不是一个字典:

data = []

推荐阅读