Home > Enterprise >  JSON re-structure using Python
JSON re-structure using Python

Time:08-10

my csv file,

"id","first name","lastname","zipcode","city"
"10001","test","sample","3333","LA"

I have converted CSV to json ,

import csv
import json

def csv_to_json(csvFilePath, jsonFilePath):
    jsonArray = []

    with open('Sample.csv', encoding='utf-8') as csvf:
        csvReader = csv.DictReader(csvf)
        
        for row in csvReader:
            jsonArray.append(row)

    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
        jsonString = json.dumps(jsonArray, indent=4)
        jsonf.write(jsonString)


csvFilePath = r'data.csv'
jsonFilePath = r'data.json'
csv_to_json(csvFilePath, jsonFilePath)

json data looks like :

[
    {
        "id": "10001",
        "firstname": "test",
        "lastname": "sample",
        "zipcode":"3333"
        "city": "LA"
    }
]

I want to convert it like

{
   "id":"10001",
   "fullname":{
      "firstname":"test",
      "lastname":"sample"
   },
   "Address":{
      "zipcode":"3333",
      "city":"LA"
   }
}

any suggestions please ?

CodePudding user response:

The solution here is manually recreating the row in a way you want to save it. In this case, you can use a small helper function to do it, before you save it to jsonArray.

def transform_row(row):
    return {'id': row['id'], 'fullname': {'firstname': row['first name'], 'lastname': row['lastname']},
            'Address': {'zipcode': row['zipcode'], 'city': row['city']}}
  • Related