简体   繁体   English

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

[英]Converting a pipe delimited CSV file to a JSON file in a certain format

I am trying to convert from a CSV file each row into JSON format. 我正在尝试将CS​​V文件的每一行都转换为JSON格式。

When I convert it to JSON it includes the square brackets at the beginning and the end, how can it be omitted?. 当我将其转换为JSON时,它在开头和结尾都包含方括号,如何将其省略? Also I am looking for a way to split piped values into a list of separate hobbies. 我也在寻找一种将管道值拆分成单独爱好列表的方法。

This is what I am getting as output: 这是我得到的输出:

[
  {
    "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",
  }
]

My desired output 我想要的输出

  {
    "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",
  }

My code: 我的代码:

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')

rows = list(reader)

There is no need to wrap it into the list since it is already a list. 由于它已经是列表,因此无需将其包装到列表中。 Removing this line will fix the brackets. 删除此线将固定支架。

for row in reader:
   row['Hobby'] = list(row['Hobby'].split('|'))

We need to split the string of hobbies and convert them to list 我们需要拆分爱好字符串并将其转换为列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM