Skip to content

Instantly share code, notes, and snippets.

@sevbo2003
Created December 2, 2022 18:49
Show Gist options
  • Save sevbo2003/02f24240ef8b22ee351fcb170b1e2ffe to your computer and use it in GitHub Desktop.
Save sevbo2003/02f24240ef8b22ee351fcb170b1e2ffe to your computer and use it in GitHub Desktop.
csv to json or vice versa convertor without any package
class make_double(str): # makes double quote
def __repr__(self):
return ''.join(('"', super().__repr__()[1:-1], '"'))
def csv_to_json(csvFile, jsonFile):
with open(csvFile, "r") as f:
first_line = f.readline().rstrip().split(",")
with open(jsonFile, "w", encoding='utf-8') as w:
s = []
for i in f.readlines():
dux = {}
line = i.strip().split(',')
for a, b in enumerate(line):
replaced = b.replace(" ", "")
if replaced.isdigit():
dux[make_double(first_line[a])] = int(replaced)
else:
dux[make_double(first_line[a].strip())] = make_double(b.strip())
s.append(dux)
w.write(str(s))
csv_to_json('homes.csv', 'data.json')
def json_to_csv(jsonFile, csvFile):
with open(jsonFile, "r") as f:
json = eval(f.read())
keys = json[0]
with open(csvFile, "w") as w:
w.write(','.join([i for i in keys.keys()]))
for i in json:
values = ','.join([str(item) for item in i.values()])
a = f"{values}\n"
w.write(a)
json_to_csv("data.json", "result.csv")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment