title: Python: csv to json converter value to key pair
body: <p>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.</p>
  
  <p>@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.</p>
  
  <p>The csv file looks like this</p>
  
  <pre><code>Document;Item;Category
  4;10;C
  </code></pre>
  
  <p>What I am getting in the output file as of now (after applying the changes from kvorobiev):</p>
  
  <pre><code>[
  {
      "Item": "10",
      "Category": "C",
      "Document": "4"
  };
  ]
  </code></pre>
  
  <p>The json string I want to get in the output file should look like:</p>
  
  <pre><code>[
  {
     "Document": "4",
     "Item": "10",
     "Category": "C"
  },
  ]
  </code></pre>
  
  <p>You will notice the headings are in the wrong order.</p>
  
  <p>Here is the code:</p>
  
  <pre><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 &lt; num_lines:
      jsonfile.write(',')
    jsonfile.write('\n')
  jsonfile.write(' ' + ']')
  
  print('Done')
  </code></pre>
  
  <p>Thanks for helping.</p>