Python - convert csv file to JSON

前端 未结 4 1338
醉梦人生
醉梦人生 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:25

    Order of elements is not important for json.

    The json you are producing is wrong, though. The example you gave that you are trying to match does not have a "subject" key at the top level. It shows just "name" => "flare", and a list of children. Your script is producing json with a "subject" key.

    Instead of

    subject_dict = {'name':subject,'type':'subject','children':branch_list}
    

    try

    subject_dict = {'name':subject,'children':branch_list}
    

    I don't know about D3.js, so I can't say if it expects an object that follows one exact structure.

    Tip: one good tool to check the structure of json objects is http://jsoneditor.appspot.com. Just paste your string in there and click on "Go to Treeview". It will hellp you find differences between what you have and what you want very easily.

    0 讨论(0)
  • 2020-12-19 05:34
    import csv
    import json
    file1 = csv.DictReader(open('filename.csv', 'r'))
    output =[]
    for each in complent:
        row = {}
        row['Id'] = each['Id']
        row['Name'] = each['Name']
        row['Address'] = each['Address']
        row['Mobile'] = each['Mobile']
        row['LandLine'] = each['LandLine']
        row['Email'] = each['Email']
        output.append(row)
    
    json.dump(output,open('new_file.json','w'),indent=4,sort_keys=False)
    
    0 讨论(0)
  • 2020-12-19 05:44

    D3 expects the value in JSON to also be in double quotes. so e.g. "level": 3 should be "level" : "3". When you use this data in D3 for calculation it will need to be a number again though so where you use it you can just use +data.xxx.yyy.level instead of data.xxx.yyy.level in the d3 code to turn it into a number.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题