How can I convert JSON to CSV?

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

    This code should work for you, assuming that your JSON data is in a file called data.json.

    import json
    import csv
    
    with open("data.json") as file:
        data = json.load(file)
    
    with open("data.csv", "w") as file:
        csv_file = csv.writer(file)
        for item in data:
            fields = list(item['fields'].values())
            csv_file.writerow([item['pk'], item['model']] + fields)
    

提交回复
热议问题