This prompt generates a Python program that reads in a CSV file for
a graph and returns a JSON file in vis.js format.
Prompt
I have a CSV file that has graph data in it.
The fields are:
ConceptID - the node id in a graph. Unique for all nodes. Required.
The ConceptName - a node label - Required
DependencyList - a pipe-delimited list of dependant ConceptIDs. An edge goes from this concept to other concepts with a directed arrow.
CategoryID - a group ID for the concept.
CategoryLabel - the name of the category
There are about 11 Categories
ConceptID,ConceptName,DependencyList,CategoryID,CategoryLabel
1,Ohm's Law,2|3|4,1,Fundamental Concepts
2,Voltage,7,1,Fundamental Concepts
3,Current,7,1,Fundamental Concepts
4,Resistance,101,1,Fundamental Concepts
5,Power,2|3,1,Fundamental Concepts
6,Energy,5|102,1,Fundamental Concepts
7,Electric charge,120,1,Fundamental Concepts
8,Conductors,7,1,Fundamental Concepts
9,Insulators,7,1,Fundamental Concepts
10,Capacitance,2|7,1,Fundamental Concepts
11,Inductance,3|104,1,Fundamental Concepts
Please create a Python program that converts this CSV file into a JSON file that can be easily read by vis.js. Assume that the category ID will become a group ID.
importcsvimportjsondefcsv_to_visjs_json(csv_filename,json_filename):nodes=[]edges=[]categories={}# Read the CSV filewithopen(csv_filename,'r',newline='',encoding='utf-8')ascsvfile:reader=csv.DictReader(csvfile)forrowinreader:# Extract node informationtry:concept_id=int(row['ConceptID'])exceptValueError:print(f"Invalid ConceptID '{row['ConceptID']}' skipped.")continue# Skip rows with invalid ConceptIDconcept_name=row['ConceptName'].strip()ifnotconcept_name:print(f"Empty ConceptName for ConceptID {concept_id} skipped.")continue# Skip nodes without a nametry:category_id=int(row['CategoryID'])exceptValueError:print(f"Invalid CategoryID '{row['CategoryID']}' for ConceptID {concept_id} skipped.")continue# Skip rows with invalid CategoryIDcategory_label=row['CategoryLabel'].strip()# Create node objectnode={'id':concept_id,'label':concept_name,'group':category_id}nodes.append(node)# Store category information (optional, for groups)ifcategory_idnotincategories:categories[category_id]=category_label# Process DependencyList to create edgesdependency_list=row['DependencyList'].strip()ifdependency_list:dependencies=dependency_list.split('|')fordepindependencies:dep=dep.strip()ifdep:try:dep_id=int(dep)edge={'from':concept_id,'to':dep_id}edges.append(edge)exceptValueError:print(f"Invalid DependencyID '{dep}' for ConceptID {concept_id} skipped.")continue# Skip invalid DependencyIDs# Optionally, create a separate groups structure if needed# Uncomment the following lines if you want to include group labels""" groups = [] for cid, clabel in categories.items(): group = { 'id': cid, 'label': clabel # You can add more styling options here if needed } groups.append(group) data = { 'nodes': nodes, 'edges': edges, 'groups': groups } """# If not using separate groups, omit the 'groups' keydata={'nodes':nodes,'edges':edges}# Write the JSON outputwithopen(json_filename,'w',encoding='utf-8')asjsonfile:json.dump(data,jsonfile,indent=4)print(f"Successfully converted '{csv_filename}' to '{json_filename}'.")if__name__=="__main__":# Define input and output file namesinput_csv='graph-data.csv'output_json='graph-data.json'# Convert CSV to JSONcsv_to_visjs_json(input_csv,output_json)