How can I convert JSON to CSV?

前端 未结 26 1619
余生分开走
余生分开走 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)
    

提交回复
热议问题