python - 将 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", ... ]
}
解决方案
而不是这个:
for line in csv_reader:
company = line[2]
data[company] = line[2]
做这个:
for line in csv_reader:
data.append(line[2])
您还需要data
列出一个列表,而不是一个字典:
data = []
推荐阅读
- python - Python / Pandas:找到一个左右最大值
- reactjs - 如何更改 MUI LinearProgress 组件的颜色?
- .net-core - 使用 IUserClaimsPrincipalFactory 向身份添加附加声明
- javascript - Acumatica 工具提示位置
- r - R将非常大的数据表列表合并为一个data.table
- javascript - 无法在模板文字中运行 for 循环
- amazon-web-services - 速率限制 AWS CloudWatch 日志摄取
- css - 如何在内嵌圆圈上添加文本?
- pandas - 根据熊猫中2个不同列中的日期运行计数
- wordpress - 如果已发布的 WP 插件更改了名称和文件结构,将更新上传到 WP 存储库的最佳方式是什么?