How to convert csv to json in python?

前端 未结 5 887
走了就别回头了
走了就别回头了 2020-12-15 22:47

I\'m very new to programming, have been learning python from past 3/4 weeks and this is one of the assignments given.

Input



        
相关标签:
5条回答
  • 2020-12-15 23:16

    For those who like one-liners:

    import csv
    import json
    
    json_data = [json.dumps(d) for d in csv.DictReader(open('file.csv'))]
    

    Checkout this fiddle for a working example: https://pyfiddle.io/fiddle/5992b8f4-552f-4970-91b6-a52cdee16ebc/?i=true

    0 讨论(0)
  • 2020-12-15 23:17

    Convert CSV to Json Python

    import csv
    import urllib2
    
    url = '<YOURCSVURL>'
    response = urllib2.urlopen(url)
    cr = csv.reader(response)
    
    line = {}
    data = []
    
    for index, row in enumerate(cr):
        if index:
            for index, col in enumerate(row):
                line[name[index]] = col
    
            data.append(line.copy())
        else:
            name = row
    
    print data
    
    0 讨论(0)
  • 2020-12-15 23:20

    Dump after processing whole rows.


    import csv
    import json
    
    with open('test.csv') as f:
        reader = csv.DictReader(f)
        rows = list(reader)
    
    with open('test.json', 'w') as f:
        json.dump(rows, f)
    
    0 讨论(0)
  • 2020-12-15 23:24

    You can attempt it using this code :

    def inputfunction(lists):
     tmpdict = {}
     for element_index in range(len(lists)):
         tmpdict[headers[elementindex]] = lists[element_index]
     return tmpdict
    
    def run(filename):
     filelist = [eachline.split(',') for eachline in open(inputfile,'r')]
     headers = filelist[0]
     values = filelist[1:]
     finallist = []
     for lists in values:
         finallist.append(inputfunction(lists))
     return finallist
    
    0 讨论(0)
  • 2020-12-15 23:34
    import csv
    import json
    
    # Constants to make everything easier
    CSV_PATH = './csv.csv'
    JSON_PATH = './json'
    
    # Reads the file the same way that you did
    csv_file = csv.DictReader(open(CSV_PATH, 'r'))
    
    # Created a list and adds the rows to the list
    json_list = []
    for row in csv_file:
        json_list.append(row)
    
    # Writes the json output to the file
    file(JSON_PATH, 'w').write(json.dumps(json_list))
    
    0 讨论(0)
提交回复
热议问题