[Python] Convert CSV to JSON file in python

Discussão em 'Python' iniciado por Stack, Agosto 21, 2025.

  1. Stack

    Stack Membro Participativo

    [​IMG] Above csv file which contains nearly 2000 rows.

    I want to parse CSV file line by line and convert it to JSON and send over websocket.

    I found some code online which converts CSV to JSON as follows:

    import csv
    import json

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

    fieldnames = ("FirstName","LastName","IDNumber","Message")
    reader = csv.DictReader( csvfile, fieldnames)
    for row in reader:
    json.dump(row, jsonfile)
    jsonfile.write('\n')


    But the problem with above code is that we need to mention the field names to parse the CSV. Since I have more than 2000 rows, it is not a feasible solution.

    Can anyone suggest how to parse CSV file line by line and convert it into JSON without specifying fieldnames?

    Continue reading...

Compartilhe esta Página