如何将带有日期的文本写入JSON文件而不序列化i

2024-10-05 14:29:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从纯文本文件中读取一些文本。在做了一些修改之后,我想写另一个包含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文件。你知道吗


Tags: 文件字符串jsondatadate序列化格式with
1条回答
网友
1楼 · 发布于 2024-10-05 14:29:53

JSON不知道任何日期或时间类型。参见table of Python types and how they map to JSON data types。你知道吗

要在JSON中表示任何不是JSON本机的类型(如日期或日期+时间),必须将其序列化:将该值转换为具有特定格式的字符序列。你知道吗

^{} class允许扩展以满足此需求:

To extend this to recognize other objects, subclass and implement a default method with another method that returns a serializable object for o if possible, otherwise it should call the superclass implementation (to raise TypeError).

您选择了iso8601序列化格式来表示日期值;这是一个很好的选择。datetime.date类型directly supports serialising to ISO representation。你知道吗

所以现在需要一个JSONEncoder子类来识别datetime.date值,并将它们序列化为iso8601:

import datetime
import json

class MySpecificAppJSONEncoder(json.JSONEncoder):
    """ JSON encoder for this specific application. """

    def default(self, obj):
        result = NotImplemented
        if isinstance(obj, datetime.date):
            result = obj.isoformat()
        else:
            result = json.JSONEncoder.default(self, obj)
        return result

现在,您的函数可以使用该编码器类:

json.dump(parsed_data, outfile, indent=4, cls=MySpecificAppJSONEncoder)

相关问题 更多 >