user87290
user87290

Reputation: 3

Python: csv to json converter value to key pair

I had a Python beginners course last year. Now I am trying to get a csv to json converter. I have searched quite some time and adapted and changed some of the code I found, until the output looked similar to what I want. I am using Python 3.4.2.

@kvorobiev this is an excerpt of my CSV, but it will do for the case. The first time Converting will work. After the second time you will see that the order of the headings will change within the json file.

The csv file looks like this

Document;Item;Category
4;10;C

What I am getting in the output file as of now (after applying the changes from kvorobiev):

[
{
    "Item": "10",
    "Category": "C",
    "Document": "4"
};
]

The json string I want to get in the output file should look like:

[
{
   "Document": "4",
   "Item": "10",
   "Category": "C"
},
]

You will notice the headings are in the wrong order.

Here is the code:

import json
import csv

csvfile = open('file1.csv', 'r')
jsonfile = open('file1.csv'.replace('.csv','.json'), 'w')

jsonfile.write('[' + '\n' + ' ')
fieldnames = csvfile.readline().replace('\n','').split(';')
num_lines = sum(1 for line in open('file.csv')) -1

reader = csv.DictReader(csvfile, fieldnames)
i = 0
for row in reader:  
  i += 1
  json.dump(row, jsonfile, indent=4,sort_keys=False)
  if i < num_lines:
    jsonfile.write(',')
  jsonfile.write('\n')
jsonfile.write(' ' + ']')

print('Done')

Thanks for helping.

Upvotes: 0

Views: 1788

Answers (1)

kvorobiev
kvorobiev

Reputation: 5070

Replace line

reader = csv.DictReader(csvfile, fieldnames)

with

reader = csv.DictReader(csvfile, fieldnames, delimiter=';')

Also, you open file1.csv and later get lines number from file.csv

num_lines = sum(1 for line in open('file.csv')) -2

Your solution could be reduced to

import json
import csv
csvfile = open('file1.csv', 'r')
jsonfile = open('file1.csv'.replace('.csv','.json'), 'w')
jsonfile.write('{\n[\n')
fieldnames = csvfile.readline().replace('\n','').split(';')
reader = csv.DictReader(csvfile, fieldnames, delimiter=';')
for row in reader:  
  json.dump(row, jsonfile, indent=4)
  jsonfile.write(';\n')
jsonfile.write(']\n}')

If you want to save order of columns from csv you could use

from collections import OrderedDict
...
for row in reader:  
  json.dump(OrderedDict([(f, row[f]) for f in fieldnames]), jsonfile, indent=4)
  jsonfile.write(';\n')
jsonfile.write(']\n}')

Upvotes: 3

Related Questions