我正在对json转换执行csv,一切正常,问题是我的最后一个字段有时会有逗号分隔值,并且解析器将其视为新列。
即:
key1 key2 key3 key4
val1 val2 val3 val4,val4.1,val4.2,val4.3
我得到了这种json:
{key1: val1, key2: val2, key3:val3, key4:val4}
并且不存在val4.1,val4.2,val4.3。 适当的结果是:
{key1: "val1", key2: "val2", key3: "val3", key4: "val4,val4.1,val4.2,val4.3"}
到目前为止我的代码:
#!/usr/bin/env python
"""Convert csv to json"""
import json
import argparse
def parse(filename):
with open(filename) as f:
csv = f.read().split('\r\n\r\n')[1]
keys = ['val1', 'val2', 'val3', 'val4']
for line in stations.split('\r\n')[1:]:
yield dict(zip(keys, [cell.strip() for cell in line.split(',')]))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-i', default='dump.csv', help='csv input file')
parser.add_argument('-o', default='state/dump.json', help='json output file')
(opt, args) = parser.parse_args()
with open(opt.o, 'w+') as f:
rows = []
for row in parse(opt.i):
rows.append(row)
json.dump(rows, f, ensure_ascii=False)
答案 0 :(得分:0)
答案实际上非常简单,只是漫长的一天,所以我没有立刻想到它。 为求职者提供的解决方案是:
代码:
keys = ['val1', 'val2', 'val3', 'val4']
for line in csv.split('\r\n')[1:]:
current_line = line.split(',')
extras = len(current_line) - len(keys)
newString = ""
for i in range(len(keys), len(keys) + extras):
if(i+1 == len(keys) + extras):
newString += current_line[i]
else:
newString += current_line[i] + ","
list = line.split(',')
list[len(keys)-1] = probes
yield dict(zip(keys, [cell.strip() for cell in list]))