How can I convert JSON to CSV?

前端 未结 26 1612
余生分开走
余生分开走 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
    import json,csv
    t=''
    t=(type('a'))
    json_data = []
    data = None
    write_header = True
    item_keys = []
    try:
    with open('kk.json') as json_file:
        json_data = json_file.read()
    
        data = json.loads(json_data)
    except Exception as e:
        print( e)
    
    with open('bar.csv', 'at') as csv_file:
        writer = csv.writer(csv_file)#, quoting=csv.QUOTE_MINIMAL)
        for item in data:
            item_values = []
            for key in item:
                if write_header:
                    item_keys.append(key)
                value = item.get(key, '')
                if (type(value)==t):
                    item_values.append(value.encode('utf-8'))
                else:
                    item_values.append(value)
            if write_header:
                writer.writerow(item_keys)
                write_header = False
            writer.writerow(item_values)
    
    0 讨论(0)
  • 2020-11-21 23:08

    Unfortunately I have not enouthg reputation to make a small contribution to the amazing @Alec McGail answer. I was using Python3 and I have needed to convert the map to a list following the @Alexis R comment.

    Additionaly I have found the csv writer was adding a extra CR to the file (I have a empty line for each line with data inside the csv file). The solution was very easy following the @Jason R. Coombs answer to this thread: CSV in Python adding an extra carriage return

    You need to simply add the lineterminator='\n' parameter to the csv.writer. It will be: csv_w = csv.writer( out_file, lineterminator='\n' )

    0 讨论(0)
提交回复
热议问题