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
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.
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)
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.
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