Python - convert csv file to JSON

前端 未结 4 1374
醉梦人生
醉梦人生 2020-12-19 04:44

I need to convert a csv file into a hierarchical JSON object (preferably using Python). I thought that the script I have (below) does a correct job of converting to JSON, bu

4条回答
  •  青春惊慌失措
    2020-12-19 05:45

    Wouldn't this work?

    import json
    
    f = open('path/to/file','r')
    
    arr=[]
    headers = []
    
    for header in f.readline().split(','):
      headers.append(header)
    
    for line in f.readlines():
      lineItems = {}
      for i,item in enumerate(line.split(',')):  
        lineItems[headers[i]] = item
      arr.append(lineItems)
    
    f.close()
    
    jsonText = json.dumps(arr)
    
    print jsonText
    

提交回复
热议问题