How can I convert JSON to CSV?

前端 未结 26 1643
余生分开走
余生分开走 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 22:53

    Since the data appears to be in a dictionary format, it would appear that you should actually use csv.DictWriter() to actually output the lines with the appropriate header information. This should allow the conversion to be handled somewhat easier. The fieldnames parameter would then set up the order properly while the output of the first line as the headers would allow it to be read and processed later by csv.DictReader().

    For example, Mike Repass used

    output = csv.writer(sys.stdout)
    
    output.writerow(data[0].keys())  # header row
    
    for row in data:
      output.writerow(row.values())
    

    However just change the initial setup to output = csv.DictWriter(filesetting, fieldnames=data[0].keys())

    Note that since the order of elements in a dictionary is not defined, you might have to create fieldnames entries explicitly. Once you do that, the writerow will work. The writes then work as originally shown.

提交回复
热议问题