Reading values from CSV file and convert it to json in python



  • my code :

    import csv
    import json
    with open('file.csv', 'r') as f:
        reader = csv.reader(f, delimiter=';')
        data_list = list()
        for row in reader:
            data_list.append(row)
    data = [dict(zip(data_list[0],row)) for row in data_list]
    data.pop(0)
    s = json.dumps(data, indent=2)
    print (s)
    

    Actual Result :

    [
      {
        "bundleParentId": " ",
        "id": "1",
        "itemType": "ART",
        "itemNo": "90411111",
        "requiredQty": "2",
        "unitOfMeasure": "Piece"
      }
    ]
    

    Expected Result ;

      {
        "bundleParentId": " ",
        "id": "1",
        "itemType": "ART",
        "itemNo": "90411111",
        "requiredQty": "2",
        "unitOfMeasure": "Piece"
      }
    


  • You can use the "json.dump" and inside that use "for loop" which will create multiple objects in string (JSON format) till the reader reaches the last row.

    For example:-

    import csv
    import json
    
    csvfile_path = open('/home/Python/Data.csv', 'r')
    jsonfile_path = open('/home/Python/Output.json', 'w')
    
    field_name = ("Continent","Country","State","Capital")
    reader = csv.DictReader( csvfile_path, field_name)
    out = json.dumps( [ row for row in reader ] )
    jsonfile_path.write(out)
    

Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2