I am reading some text from a plain text file. After doing some modifications, I want to write another file containing JSON which also has date format in it.
When I try to convert it to JSON using json.dumps
, it gives:
Object of type 'datetime' is not JSON serializable
When I seralise it and write it to file, it works fine. But now the date is represented in string format. I want to be in JSON ISO date format
.
Here is my code:
def getDatetimeFromISO(s):
d = dateutil.parser.parse(s)
return d
with open('./parsedFiles/Data.json','w+') as f:
parsedData = []
for filename in os.listdir('./Data'):
parsed = {}
parsed["Id"] = filename[:-4]
breakDown = []
with open('./castPopularityData/'+str(filename),'r') as f1:
data = ast.literal_eval(f1.read())
for i in range(0,len(data)):
data[i]["date"] = getDatetimeFromISO(data[i]['date'])
data[i]["rank"] = data[i]['rank']
breakDown.append(data[i])
parsed["breakDown"] = breakDown
parsedData.append(parsed)
print(parsedData)
json.dump(parsedData, f, indent=4)
How can i write the ISO date to JSON file?
I don't want to serialize my data, which makes date format into string. I want to write dates as dates itself to JSON file.