我正在从纯文本文件中读取一些文本。在做了一些修改之后,我想写另一个包含JSON的文件,其中也包含日期格式。你知道吗
当我尝试使用json.dumps
将其转换为JSON时,它给出:
Object of type 'datetime' is not JSON serializable
当我将它序列化并写入文件时,它工作得很好。但是现在日期是用字符串格式表示的。我想在JSON ISO date format
。你知道吗
这是我的密码:
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)
如何将ISO日期写入JSON文件?你知道吗
我不想序列化数据,这会使日期格式变成字符串。我想将日期作为日期本身写入JSON文件。你知道吗
JSON不知道任何日期或时间类型。参见table of Python types and how they map to JSON data types。你知道吗
要在JSON中表示任何不是JSON本机的类型(如日期或日期+时间),必须将其序列化:将该值转换为具有特定格式的字符序列。你知道吗
^{} class 允许扩展以满足此需求:
您选择了iso8601序列化格式来表示日期值;这是一个很好的选择。
datetime.date
类型directly supports serialising to ISO representation。你知道吗所以现在需要一个JSONEncoder子类来识别
datetime.date
值,并将它们序列化为iso8601:现在,您的函数可以使用该编码器类:
相关问题 更多 >
编程相关推荐