recurrenceprobs
recurrenceprobs

Reputation: 13

Converting a CSV file to JSON in python

So I'm trying to load in the data in csvfile, convert it to a list of dictionaries and then save the result as JSON to jsonfile. This is what I have right now. When I try to open and load the json file, I get a "ValueError: No JSON object could be decoded" I'd appreciate any tips!

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)

Upvotes: 0

Views: 149

Answers (3)

Amanda
Amanda

Reputation: 12757

I wound up with this, to write arbitrary CSVs:

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)

Upvotes: 0

Fujiao Liu
Fujiao Liu

Reputation: 2253

try this:

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                  

Upvotes: 1

xecgr
xecgr

Reputation: 5193

Remember JSON isn't the same that python objects/dictionaries, have a look to this answer
So, you must use json.dumps to encode it, and then json.loads to decode it back to a valid python dict

Upvotes: 0

Related Questions