2014-11-17 43 views
0

因此,我试图加载csvfile中的数据,将其转换为字典列表,然后将结果保存为JSON到jsonfile。这就是我现在所拥有的。当我尝试打开并加载json文件时,我得到一个“ValueError:没有JSON对象可以解码”我会很感激任何提示!在python中将CSV文件转换为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) 

回答

0

记住JSON是不一样的是Python对象/字典,看看这个answer
所以,你必须使用json.dumps进行编码,然后json.loads到回解码为有效的Python字典

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