How can I convert JSON to CSV?

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

    My simple way to solve this:

    Create a new Python file like: json_to_csv.py

    Add this code:

    import csv, json, sys
    #if you are not using utf-8 files, remove the next line
    sys.setdefaultencoding("UTF-8")
    #check if you pass the input file and output file
    if sys.argv[1] is not None and sys.argv[2] is not None:
    
        fileInput = sys.argv[1]
        fileOutput = sys.argv[2]
    
        inputFile = open(fileInput)
        outputFile = open(fileOutput, 'w')
        data = json.load(inputFile)
        inputFile.close()
    
        output = csv.writer(outputFile)
    
        output.writerow(data[0].keys())  # header row
    
        for row in data:
            output.writerow(row.values())
    

    After add this code, save the file and run at the terminal:

    python json_to_csv.py input.txt output.csv

    I hope this help you.

    SEEYA!

提交回复
热议问题