pythonjsoncsvcsvtojson

How can I make JSON file from a CSV?


I have a CSV file with 4 columns(A, B, C, D). Like this:

A B C D
Example english text Translated text Context Max Length
Example english text 2 Translated text 2 Context 2 Max Length 2
Example english text 3 Translated text 3 Context 3 Max Length 3

And I need a code, that makes transforms that, to this JSON file:

{
  "Context": "Translated text",
  "Context 2": "Translated text 2",
  "Context 3": "Translated text 3"
}

I tried this:

import csv
import json


def make_json(csvFilePath, jsonFilePath):
    
    data = {}
    
    with open(csvFilePath, encoding='utf-8') as csvf:
        csvReader = csv.DictReader(csvf)
        
        for rows in csvReader:
            
            key = rows["C"]
            data[key] = rows


    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
        jsonf.write(json.dumps(data, indent=4))
        

csvFilePath = "main.csv"
jsonFilePath = "test.json"

make_json(csvFilePath, jsonFilePath)

But there's an error, and i'm not sure this is the best method.

How can i fix this?

The Error:

D:\Python\CSV to JSON>py csvtojson.py
Traceback (most recent call last):
  File "D:\Python\CSV to JSON\csvtojson.py", line 25, in <module>
    make_json(csvFilePath, jsonFilePath)
  File "D:\Python\CSV to JSON\csvtojson.py", line 14, in make_json
    key = rows["C"]
KeyError: 'C'

Thank you for the help!


Solution

  • This should do-

    import csv
    
    with open('data.csv', 'r') as f:
        csv_data = csv.reader(f)
        json_data = {data[2]: data[1] for data in csv_data}
        
    with open('data.json', 'w') as f:
        json.dump(json_data, f, indent=4)