How can I convert JSON to CSV?

前端 未结 26 1616
余生分开走
余生分开走 2020-11-21 22:32

I have a JSON file I want to convert to a CSV file. How can I do this with Python?

I tried:

import json
import c         


        
26条回答
  •  情深已故
    2020-11-21 23:03

    It is not a very smart way to do it, but I have had the same problem and this worked for me:

    import csv
    
    f = open('data.json')
    data = json.load(f)
    f.close()
    
    new_data = []
    
    for i in data:
       flat = {}
       names = i.keys()
       for n in names:
          try:
             if len(i[n].keys()) > 0:
                for ii in i[n].keys():
                   flat[n+"_"+ii] = i[n][ii]
          except:
             flat[n] = i[n]
       new_data.append(flat)  
    
    f = open(filename, "r")
    writer = csv.DictWriter(f, new_data[0].keys())
    writer.writeheader()
    for row in new_data:
       writer.writerow(row)
    f.close()
    

提交回复
热议问题