Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON to CSV

Tags:

python

json

csv

In python I have a complex object hierarchy made of lists and dictionaries. I want to spit it all out to CSV or some other kind of database format. Any answers in Python or Javascript very much appreciated.

I understand that one CSV file (or table) can only represent one 'level' of object in my hierarchy, so the solution would need to create multiple files.

Here is an example:

{
    "Person" : [{"name":"Greg","age":"35","car":["honda civic","ford focus"]},
                {"name":"Steve","age":"28", "car":["mazda 323", "toyota camry"]}]
}

would become

Person.csv:
id,name,age
1,Greg,35
2,Steve,28

car.csv:
id,Person_id,value
1,1,honda civic
2,1,ford focus
3,2,mazda 323
4,2,toyota camry

Basically the only thing interesting going on here is the assignment of new ids so that the rows in the tables can be associated.

Cheers, Dave

like image 797
Trindaz Avatar asked Nov 06 '22 07:11

Trindaz


1 Answers

try something like this.

json_dict = {
    "Person" : [{"name":"Greg","age":"35","car":["honda civic","ford focus"]},
                {"name":"Steve","age":"28", "car":["mazda 323", "toyota camry"]}]
}

for entity in json_dict:
    csv_file = open('%s.csv' % entity, 'wb')
    headers = a[entity][0].keys()
    csv_writer = csv.DictWriter(csv_file, headers)
    map(csv_writer.writerow, json_dict[entity])
    csv_file.close()

# Now you have your json to csv file for formatting you can use awk;

awk  -F , '{print NR ", " $2 ", " $3 }' Person.csv > person.csv

...

like image 124
mouad Avatar answered Nov 09 '22 02:11

mouad