How can I convert JSON to CSV?

前端 未结 26 1662
余生分开走
余生分开走 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:08

    A generic solution which translates any json list of flat objects to csv.

    Pass the input.json file as first argument on command line.

    import csv, json, sys
    
    input = open(sys.argv[1])
    data = json.load(input)
    input.close()
    
    output = csv.writer(sys.stdout)
    
    output.writerow(data[0].keys())  # header row
    
    for row in data:
        output.writerow(row.values())
    

提交回复
热议问题