CSV to JSON using python


I want to populate my json message with data from a CSV file. I want each row to be a “new” json message. I am using python and will connect the the code to an API once done. Some of the data is categorized under “personalinfo” and “carinfo” and I need the correct data to be populated under the right category as under the “expected json message output”

This is what I have so far:

> import csv 
import pandas as pd 
import json 
import sys 
import re   
> csvfile = open('test.csv', 'r') jsonfile = open('file.json', 'w')
> fieldnames = ("firstname","r", "lastname","r", "age","r","gender",
> "r", "model", "r", "price","r","loan","r") 
>reader = csv.DictReader(csvfile, fieldnames) out = json.dumps( [ row for >row in
> reader ] ) jsonfile.write(out)

I do not know how to add the “categorize”

Example csv table:

 FirstName  LastName    Age gender  Car model Price loan
    Anna    Andersson   28  F       Audi    A8 40    FALSE
    Bea    Bertilsson   27  F       WV      GT 20    TRUE

expected json message output:

    "personalinfo": {
        "firstname": "Anna",
        "lastname": "Andersson",
        "age": "28",
        "gender": "F",

        "carinfo": [{
            "car  ": "Audi",
            "model": "A8"

        "price": 40,
        "loan": "FALSE"


Next record should be a new json file

    "personalinfo": {
        "firstname": "Bea",
        "lastname": "Bertilsson",
        "age": "27",
        "gender": "F",

        "carinfo": [{
            "car  ": "WV",
            "model": "GT"

        "price": 20,
        "loan": "TRUE"



Have you tried anything or are you asking us to do it for you?
What have you tried so far?
Well… that output isn’t valid JSON… How far have you got with that, and is your source data a pandas DataFrame or is that just how you’ve presented the data?
@johnashu added the code
– hlch123
27 secs ago



Tags:, ,