CSV to JSON Conversion Function

  • Share this:

Code introduction


This function reads data from a CSV file, then converts these data into JSON format and writes it to another file.


Technology Stack : csv, json

Code Type : Data processing function

Code Difficulty : Intermediate


                
                    
def extract_json_from_csv(input_csv, output_json):
    import csv
    import json

    # Initialize an empty list to store rows from CSV
    csv_data = []
    
    # Open the CSV file and read each row
    with open(input_csv, mode='r', encoding='utf-8') as csvfile:
        csv_reader = csv.DictReader(csvfile)
        for row in csv_reader:
            csv_data.append(row)
    
    # Convert the list of dictionaries to JSON
    json_data = json.dumps(csv_data, indent=4)
    
    # Write the JSON data to a file
    with open(output_json, mode='w', encoding='utf-8') as jsonfile:
        jsonfile.write(json_data)                
              
Tags: