在python中将CSV文件转换为JSON

时间:2014-11-17 05:57:25

标签: python json

所以我试图加载csvfile中的数据,将其转换为字典列表,然后将结果作为JSON保存到jsonfile。这就是我现在所拥有的。当我尝试打开并加载json文件时,我得到一个" ValueError:No JSON对象可以被解码"我很感激任何提示!

def csv_to_json(csvfile, jsonfile):
    reader = csv.DictReader(csvfile.splitlines(), delimiter=' ', skipinitialspace=True,
                        fieldnames=['dept', 'code', 'section',
                                    'name', 'instructor', 'type','location])
    writer = csv.DictWriter(open(jsonfile,'wb'), fieldnames=reader.fieldnames)

3 个答案:

答案 0 :(得分:1)

试试这个:

import json
import csv


def csv_to_json(csvfile, jsonfile):
    ''''''
    with open(csvfile, 'rb') as f:
       reader = csv.DictReader(f, delimiter=',', fieldnames=['head1', 'head2']) 
       open(jsonfile, 'w').write(json.dumps(list(reader)) # if your csv file is not very large                  

答案 1 :(得分:0)

记住JSON与python对象/词典不同,请查看answer
因此,您必须使用json.dumps对其进行编码,然后使用json.loads将其解码回有效的python dict

答案 2 :(得分:0)

我结束了这一点,写了任意的CSV:

import json
import csv

def csv_to_json(csvfile, jsonfile):
    """
    Read a CSV file and output it as JSON. Assumes the csv has a header row.
    """
    with open(csvfile, 'rU') as f:
        reader = csv.DictReader(f)
        data_dict = []
        for row in reader:
            data_dict.append(row)
        print(len(data_dict))
        with open(jsonfile, 'w') as g:
            json.dump(data_dict, g)