Python to convert CSV to JSON

Python to convert CSV to JSON
python
Ethan Jackson

I need to convert below csv file to json

cat /tmp/input.csv ID,item,name 1,A,aname 2,A,bname 6,A,zname 8,A,xname

expected json

{ "filters": [ { "ID":1, “item”:A, "details": { "name": "aname" } }, { "ID":2, "item":A, "details": { "name": "bname" } }, { "ID":6, "item":A, "details": { "name": "zname" } }, { "ID":8, "item":A, "details": { "name": "xname" } } ] }

I tried below workaround but unable to achieve the expected output. how do include "filters" and keep "name" inside "details" which is in expected output ?

cat /tmp/input.csv| python -c 'import csv, json, sys; print(json.dumps([dict(r) for r in csv.DictReader(sys.stdin)]))'

Answer

First, create the outer structure:

output = { "filters": [], }

Then fill in the inner filters list with the csv items:

with open('input.csv') as f: for item in csv.DictReader(f): output["filters"].append(item)

Related Articles