0

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)

3 Answers 3

1

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                  
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.