将管道分隔的CSV文件转换为某种格式的JSON文件

时间:2018-10-14 09:41:44

标签: python json python-2.7 list csv

我正在尝试将CS​​V文件的每一行都转换为JSON格式。

当我将其转换为JSON时,它在开头和结尾都包含方括号,如何将其省略?另外,我也在寻找一种将管道值拆分为单独爱好列表的方法。

这就是我得到的输出:

[
  {
    "Name": "John",
    "Age": "23",
    "Hobby": "Kayaking|Football",
    "Location": "Miami",
    "Profession": "Sales",
  },
  {
    "Name": "Peter",
    "Age": "35",
    "Hobby": "Football|Basketball|Swimming",
    "Location": "Turin",
    "Profession": "Mechanic",
  },
  {
    "Name": "James",
    "Age": "50",
    "Hobby": "Golf",
    "Location": "Berlin",
    "Profession": "Accountant",
  }
]

我想要的输出

  {
    "Name": "John",
    "Age": "23",
    "Hobby": ["Kayaking","Football"],
    "Location": "Miami",
    "Profession": "Sales",
  },
  {
    "Name": "Peter",
    "Age": "35",
    "Hobby": ["Football","Basketball","Swimming"],
    "Location": "Turin",
    "Profession": "Mechanic",
  },
  {
    "Name": "James",
    "Age": "50",
    "Hobby": "Golf",
    "Location": "Berlin",
    "Profession": "Accountant",
  }

我的代码:

import glob
import os
import csv
import json


if __name__ == '__main__':
    csv.register_dialect('piper', delimiter='|', quoting=csv.QUOTE_NONE)
    for filename in glob.glob('path_to_csv\file.csv'):
        csvfile = os.path.splitext(filename)[0]
        jsonfile = 'jsfile.json'
        fieldnames = ("Name","Age","Hobby","Location", "Profession")
    with open(csvfile+'.csv') as f:
        reader = csv.DictReader(f,fieldnames)#, dialect='piper')
        rows = list(reader)


    with open(jsonfile, 'w') as f:
        json.dump(rows, f, sort_keys=True, indent=2, separators=(',', ': '))
        f.write('\n')

1 个答案:

答案 0 :(得分:0)

Uri(urlString)

由于已经是列表,因此无需将其包装到列表中。删除此行将固定括号。

rows = list(reader)

我们需要拆分爱好字符串并将其转换为列表