I have a csv that is in the following format:
p1,p2,p3,p4,p5,p6,p7,p8,p9
u1,u2,u3,u4,u5,u6,u7,u8,u9
10,500,10,10,6.192187,0,0,10.3313,8.58659
2,150,5,3,6.7125,8.497266,9.130859,6.46657,7.645142111
,,,4,6.960938,9.472656,,6.64784,8.060439698
,,,5,7.819531,0,0,6.88975,8.972818303
where 'p' represents properties and 'u' represents units. Note that there are missing values when subsequent values are the same for that column. Unfortunately I cannot pad them.
My aim is to convert the csv to JSON using python. The format should be something like the following structure:
val1:{
val2:{
val3:{ [val4,val5,val6,val7,val8,val9]
}}}
val1:{
val2:{
val3:{ [val4,val5,val6,val7,val8,val9],
[val4,val5,val6,val7,val8,val9],
[val4,val5,val6,val7,val8,val9],
}}}
Note that the first two lines can be ignored. I have the following python code to start with :
import csv
import json
# Function to convert a CSV to JSON
# Takes the file paths as arguments
def make_json(csvFilePath, jsonFilePath):
# create a dictionary
data = {}
# Open a csv reader called DictReader
with open(csvFilePath, mode='r', encoding='utf-8-sig') as csvf:
csvReader = csv.DictReader(csvf,delimiter =',')
for rows in csvReader:
# Assuming a column named 'p1' to
# be the primary key
key = rows['p1']
data[key] = rows
# Open a json writer, and use the json.dumps()
# function to dump data
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
jsonf.write(json.dumps(data, indent=4))
# Driver Code
# Decide the two file paths according to your
# computer system
csvFilePath = r'./data/chart-0.csv'
jsonFilePath = r'./js/try.js'
# Call the make_json function
make_json(csvFilePath, jsonFilePath)
How should I go about this?