python:csv到json创建用逗号分隔的元素

时间:2018-04-30 17:21:46

标签: python json python-3.x

我能够将csv转换为json文件。现在,我可以通过字段名称创建JSON文件,请参阅当前输出部分。

“team_members”字段中有多个名称以“,”分隔。如何通过python将team_members名称转换为Element?

数据:(demo.csv)

id,team_name,team_members
123,Biology,"Ali Smith, Jon Doe"
234,Math,Jane Smith 
345,Statistics ,"Matt P, Albert Shaw"
456,Chemistry,"Andrew M, Matt Shaw, Ali Smith"
678,Physics,"Joe Doe, Jane Smith, Ali Smith "

Python代码:

import csv
import json

csvfile = open('files/csv/input/demo.csv', 'r')
jsonfile = open('files/csv/input/demo.csv', 'w')

fieldnames = ("id",
              "team_name",
              "team_members")
reader = csv.DictReader( csvfile) # without headers
# reader = csv.DictReader( csvfile, fieldnames) # with headers
for row in reader:
    json.dump(row, jsonfile)
    jsonfile.write('\n')

当前输出:为json文件提供字段

{"id": "123", "team_name": "Biology", "team_members": "Ali Smith, Jon Doe"}
{"id": "234", "team_name": "Math", "team_members": "Jane Smith "}
{"id": "345", "team_name": "Statistics ", "team_members": "Matt P, Albert Shaw"}
{"id": "456", "team_name": "Chemistry", "team_members": "Andrew M, Matt Shaw, Ali Smith"}
{"id": "678", "team_name": "Physics", "team_members": "Joe Doe, Jane Smith, Ali Smith "}

需要最终输出:

{"id": "123", "team_name": "Biology", "team_members": ["Ali Smith", "Jon Doe"]}
{"id": "234", "team_name": "Math", "team_members": ["Jane Smith"]},
{"id": "345", "team_name": "Statistics ", "team_members": ["Matt P", "Albert Shaw"]}
{"id": "456", "team_name": "Chemistry", "team_members": ["Andrew M", "Matt Shaw", "Ali Smith"]}
{"id": "678", "team_name": "Physics", "team_members": ["Joe Doe", "Jane Smith", "Ali Smith "]} 

3 个答案:

答案 0 :(得分:1)

您可能需要查看string.split以解决此问题:

row['team_members'] = row['team_members'].split(', ')

这将用逗号分隔数组替换"team_members"字段。

答案 1 :(得分:0)

with open(csvfilepath) as infile, open('outfile.json','w') as outfile: 
    for line in infile: 
         row = dict()
         id, team_name, *team_members = line.split(',')
         row["id"] = id; row["team_name"] = team_name; row["team_members"] = team_members
         outfile.write(json.dumps(row))

答案 2 :(得分:0)

 for row in reader:
     row['team_members'] = row['team_members'].split(',')
     json.dump(row, jsonfile)
     jsonfile.write('\n')