Skip to content Skip to sidebar Skip to footer

Converting The Csv File To Specified Json Format

I am new to Python and don't know how to achieve this. I am trying to convert CSV file to JSON format. Address have types 1. Primary 2. Work and Address is multi value attribute as

Solution 1:

You were close. This should do too exactly what aim to do.

df = pd.read_csv("data.csv", sep="|")
df

enter image description here

dic = {}
for name, groupin df.groupby(by=["name"]):
    dic["name"] = name
    dic["parsed_address"] = []
        for address_type, groupin df.groupby(by=["address_type"]):
            address_dic = {}
            address_dic["address_type"] = address_type
            address_dic["address"] = group.drop(columns=["name", "address_type"]).to_dict(orient="records")
            dic["parsed_address"].append(address_dic)
dic

enter image description here

Solution 2:

I think you can try having a dictionary or list (json_data in the code below) to keep track of a person's data and iterating throw each row of the dataframe using for _, row in df.iterrows():

import pandas as pd

df = pd.read_csv("file", delimiter='|')
print(df)

json_data = {}
for _, row in df.iterrows():
    name = row["name"]
    address_type = row["address_type"]
    address_line_1 = row["address_line_1"]
    city = row["city"]
    state = row["state"]
    postal_code = row["postal_code"]
    country = row["country"]
    if name notin json_data:
        json_data[name] = {
            "name": name,
            "parsed_address": []
        }

    address_list = Nonefor address in json_data[name]["parsed_address"]:
        if address["address_type"] == address_type:
            address_list = address
    
    if address_list isNone:
        address_list = {
            "address_type": address_type,
            "address": []
        }
        json_data[name]["parsed_address"].append(address_list)
    
    address_list["address"].append({
        "address_line_1": address_line_1,
        "city": city,
        "state": state,
        "postal_code": postal_code,
        "country": country
    })

lst = list(json_data.values())

# Verify data parsingimport json
print(json.dumps(lst, indent=2))

Solution 3:

dic = {}
g_cols = ['id','first_name','last_name','address_type]
    forname, group in df.groupby(g_cols)["address"]:
        id = name[0]
        dic["id"] = id
        dic["parsed_address"] = []
        foraddress_type, group in df.groupby(by=["address_type"]):
            address_dic = {}
            address_dic["address_type"] = address_typeaddress_dic["address"] = group.drop(
                columns=["id", "first_name","last_name","address_type"]).to_dict("record")
            dic["parsed_address"].append(address_dic)

Post a Comment for "Converting The Csv File To Specified Json Format"