How can I convert JSON to CSV?

前端 未结 26 1609
余生分开走
余生分开走 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 code works for any given json file

    # -*- coding: utf-8 -*-
    """
    Created on Mon Jun 17 20:35:35 2019
    author: Ram
    """
    
    import json
    import csv
    
    with open("file1.json") as file:
        data = json.load(file)
    
    
    
    # create the csv writer object
    pt_data1 = open('pt_data1.csv', 'w')
    csvwriter = csv.writer(pt_data1)
    
    count = 0
    
    for pt in data:
    
          if count == 0:
    
                 header = pt.keys()
    
                 csvwriter.writerow(header)
    
                 count += 1
    
          csvwriter.writerow(pt.values())
    
    pt_data1.close()
    

提交回复
热议问题