Skip to content Skip to sidebar Skip to footer

How To Convert CSV File To A Specific JSON Format With Nested Objects?

I want to populate my json message with data from a CSV file. I want each row to be a 'new' json object. I am using Python and will connect the the code to an API once done. Some o

Solution 1:

You need to convert each row of data in the csv file into a JSON object laid-out the way you described. This can be accomplished by calling a single function which takes the row dictionaries from the csv file using a csv.DictReader and does just that:

import csv
import json

def make_record(row):
    return {
               "personalinfo": {
                   "firstname": row["FirstName"],
                   "lastname": row["LastName"],
                   "age": row["Age"],
                   "gender": row["gender"],
                   "carinfo": [
                       {
                           "car": row["Car"],
                           "model": row["model"]
                       }
                   ],
                   "price": int(row["Price"]),
                   "loan": row["loan"]
               }
           }


with open('csv_test.csv', 'r', newline='') as csvfile, \
     open('json_file.json', 'w') as jsonfile:
    reader = csv.DictReader(csvfile, delimiter='\t')
    out = json.dumps([make_record(row) for row in reader], indent=4)
    jsonfile.write(out)

# Show results.
with open('json_file.json', 'r') as jsonfile:
    print('results:')
    print(json.dumps(json.load(jsonfile), indent=4))


Post a Comment for "How To Convert CSV File To A Specific JSON Format With Nested Objects?"