I want to convert a CSV file containing data into JSON format to import it into another software.
I have issues regarding how Python handles JSON data.
Here's what CSV file looks like :
Date;Message;login
29/01/2019 15:38:55;Login successfull;user1
29/01/2019 15:38:44;Logout;user1
29/01/2019 15:31:12;Login successfull;user1
Here's my Code :
#-*- coding: UTF-8 -*-
from collections
import namedtuple
import csv
import json
import hashlib
import datetime
import os
headers = namedtuple ("Headers", "Date, Message, Login")
csv_file_name = 'test.csv'
json_file_name = 'output.json'
json_data = []
json_line = {}
if (os.path.lexists(json_file_name)):
os.remove(json_file_name)
json_file = open (json_file_name,'w')
with open(csv_file_name, encoding="UTF-8", newline='') as csvfile:
next(csvfile)
csv_data = csv.reader(csvfile, delimiter=';')
for header in map(headers._make, csv_data):
logDatetime = datetime.datetime.strptime(header.Date, '%d/%m/%Y %H:%M:%S')
Message = header.Message
login = hashlib.sha512(bytes(header.Login, 'UTF-8')).hexdigest()
json_line["Date"] = logDatetime.strftime('%d-%m-%Y %H:%M:%S')
json_line["Message"] = Message
json_line["Login"] = login
json_data.append(json_line)
with open (json_file_name,'w') as output :
json.dump(json_data, output, indent=4)
output.write('\n')
Here's the Data structure generated by code :
[
{
"Date": "29-01-2019 15:31:12",
"Message": "Login successfull",
"Login": "9ec62c20118ff506dac139ec30a521d12b9883e55da92b7d9adeefe09ed4e0bd152e2a099339871424263784f8103391f83b781c432f45eccb03e18e28060d2f"
},
{
"Date": "29-01-2019 15:31:12",
"Message": "Login successfull",
"Login": "9ec62c20118ff506dac139ec30a521d12b9883e55da92b7d9adeefe09ed4e0bd152e2a099339871424263784f8103391f83b781c432f45eccb03e18e28060d2f"
},
{
"Date": "29-01-2019 15:31:12",
"Message": "Login successfull",
"Login": "9ec62c20118ff506dac139ec30a521d12b9883e55da92b7d9adeefe09ed4e0bd152e2a099339871424263784f8103391f83b781c432f45eccb03e18e28060d2f"
} ]
I can't figure why my code overwrites the previous entries in the JSON data with the new one. I would be gratefull if someone could explain this to me.