0

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!

Balla Botond
  • 55
  • 11
  • What have you tried so far? – Klaus D. Sep 04 '21 at 17:53
  • Welcome to SO. Please take the [tour](https://stackoverflow.com/tour), read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) and [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). This is possible. Please write some code, post the output and any stacktraces. – Michael Ruth Sep 04 '21 at 17:53

2 Answers2

1

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)
ishmam
  • 96
  • 2
0

You can use Pandas for it, its will late you do it with very few lines of code.

import pandas as pd
# Read the csv file into Python with help from Pandas
df = pd.read_csv('csv-file.csv')

# Work with your json data in Python
json_data = df.to_json(orient = 'records')

# Save your data into new json file
df.to_json("path\example.json", orient = 'records')

Then you load a CSV file into python and convert it to JSON and you are good to go! :)

If you did not have pandas just pip it in

pip install pandas
ParisNakitaKejser
  • 12,112
  • 9
  • 46
  • 66