2014-11-17 108 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)