How can I convert JSON to CSV?

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

    This is a modification of @MikeRepass's answer. This version writes the CSV to a file, and works for both Python 2 and Python 3.

    import csv,json
    input_file="data.json"
    output_file="data.csv"
    with open(input_file) as f:
        content=json.load(f)
    try:
        context=open(output_file,'w',newline='') # Python 3
    except TypeError:
        context=open(output_file,'wb') # Python 2
    with context as file:
        writer=csv.writer(file)
        writer.writerow(content[0].keys()) # header row
        for row in content:
            writer.writerow(row.values())
    

提交回复
热议问题