Skip to content

Instantly share code, notes, and snippets.

@mszkb
Last active February 7, 2021 15:55
Show Gist options
  • Save mszkb/e7c0d45cdf29e552ff24616cebaff429 to your computer and use it in GitHub Desktop.
Save mszkb/e7c0d45cdf29e552ff24616cebaff429 to your computer and use it in GitHub Desktop.
very simple csv to json converter
# converts a csv file to json
# naiv and compressed mode
#
# naiv: a typical json file as object key-value pair format
# compressed: no keys, only values as array; headers are kept in a list
# columns: [a, b, c]
# list: [[x, y, z], [x1, y1, z1], [x2, y2,z2]
import csv
import json
def nodes(mode="naiv"):
print("printing nodes")
if (mode == "n" or mode == "naiv"):
with open('nodes.csv', 'r') as csvfile:
with open('nodes.json', 'w', encoding='utf8') as jsonfile:
reader = csv.DictReader(csvfile, delimiter=';')
json.dump(list(reader), jsonfile)
if (mode == "c" or mode == "compressed"):
results = []
# add column array for orientiation
with open('nodes.csv', 'r') as csvfile:
with open('nodes2.json', 'w', encoding='utf8') as jsonfile:
reader = csv.reader(csvfile, delimiter=';')
# get the first row for the headers array as indicator
i = next(reader)
for row in reader:
results.append(row)
nodes = {
"headers": list(i),
"nodes": results
}
json.dump(nodes, jsonfile)
def links():
print("printing links")
f = open("links.json", "w+")
f.close()
f = open("links.json", "a+")
f.write("{\n\"links\": \n\t[\n")
with open("links.csv", encoding='utf-8') as csvf:
lines = csvf.readlines()[1:]
length = len(lines) - 1
for num, line in enumerate(lines):
x = line.split(";")
source = x[0]
destination = x[1].rstrip("\n")
f.write("\t\t[" + source + "," + destination + "]")
# last item does not have ','
if length != num:
f.write(",\n")
f.write("\n\t]\n}")
f.close()
if __name__ == "__main__":
nodes("c")
#links()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment