Home > Enterprise >  Convert CSV into Json in Python. Format problem
Convert CSV into Json in Python. Format problem

Time:11-27

I have written a python code to convert csv file into json file. But the output is not the same as I desired. please look and suggest modifications.

Below is the expected json file.

[
    {
        "id": "1",
        "MobileNo": "923002546363"

    },
    {
        "id": "2",
        "MobileNo": "923343676143"

    }
]

below is the code that I have written in python.

import csv, json 

def csv_to_json(csvFilePath, jsonFilePath):
    jsonArray = []
      
    #read csv file
    with open(csvFilePath, encoding='utf-8') as csvf: 
        #load csv file data using csv library's dictionary reader
        csvReader = csv.DictReader(csvf) 

        #convert each csv row into python dict
        for row in csvReader: 
            #add this python dict to json array
            jsonArray.append(row)
  
    #convert python jsonArray to JSON String and write to file
    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf: 
        jsonString = json.dumps(jsonArray, indent=4)
        jsonf.write(jsonString)
          
csvFilePath = r'my_csv_data.csv'
jsonFilePath = r'data.json'
csv_to_json(csvFilePath, jsonFilePath)

CodePudding user response:

As your post doesn't provide current output, I just created a csv file to run your code:

id,MobileNo
1,923002546363
2,923343676143
3,214134367614

And works just fine:

[
    {
        "id": "1",
        "MobileNo": "923002546363"
    },
    {
        "id": "2",
        "MobileNo": "923343676143"
    },
    {
        "id": "3",
        "MobileNo": "214134367614"
    }
]

Check if your csv file isn't corrupted. And if possible, edit your post with current output and your csv file.

  • Related