TypeError(f'Object of type{o._class__._name__})TypeError:function类型的对象不可JSON序列化

2024-04-18 23:54:38 发布

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

我试图写一个代码来跟踪屏幕时间的使用情况。我在尝试向JSON文件添加内容时遇到了这个问题。我不知道它是什么,因为我对Python还是比较陌生的,这里的所有其他类似问题的答案都非常混乱,以至于我不理解,也没有找到一个适合我的案例的最终解决方案

在这之前有很多,但这是相关的代码:

        elif load_json == False:
            # JSON wont load if empty and if that is the case then this line will activate
            data["activities"].append(self.process_json(data))
            added_to_existing = True

        if added_to_existing == False:
            # If this window is the first instance in Json file, it must create a new dict
            data["activities"].append(self.process_json(data))

        first_time = False
        with open("Screentime/activities.json", "w") as json_file:
            json.dump(data, json_file, indent=4, sort_keys=True)
        return data

    def process_json(self, data):
        current_window_data = {
            "name": self.active_window,
            "time_entry": [TimeEntries.specific_times],
        }
        return current_window_data

class TimeEntries:
    def __init__(self, start_time_dt, end_time_dt):
        self.start_time_dt = start_time
        self.end_time_dt = end_time_dt
        self.start_time = self.start_time_dt.strftime("%Y-%m-%d %H:%M:%S")
        self.end_time = self.end_time_dt.strftime("%Y-%m-%d %H:%M:%S")
        self.days = 0
        self.hours = 0
        self.minutes = 0
        self.seconds = 0

    def specific_times(self):
        total_time = end_time - start_time
        print(total_time)
        self.days, self.seconds = total_time.days, total_time.seconds
        print(self.days)
        self.hours = self.days * 24 + self.seconds // 3600
        print(self.hours)
        self.minutes = (self.seconds % 3600) // 60
        print(self.minutes)
        self.seconds = self.seconds % 60
        print(self.seconds)

        return_list = {
            "start_time": self.start_time,
            "end_time": self.end_time,
            "days": self.days,
            "hours": self.hours,
            "minutes": self.minutes,
            "seconds": self.seconds,
        }
        return return_list

这引发的错误是:

...
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\json\encoder.py", line 431, in _iterencode
    yield from _iterencode_dict(o, _current_indent_level)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\json\encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\json\encoder.py", line 325, in _iterencode_list
    yield from chunks
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\json\encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\json\encoder.py", line 438, in _iterencode
    o = _default(o)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '

TypeError: Object of type function is not JSON serializable

如果有人能用简单的英语解释发生了什么以及如何解决这个问题,请回答


Tags: inselfjsondatatimelinedtfiles
1条回答
网友
1楼 · 发布于 2024-04-18 23:54:38

我只是把所有的东西都添加到了主类中。我认为班级之间的转换一定是个问题。虽然我仍然不明白为什么以前的代码不起作用,尽管这段代码更脏,也没有那么有条理,但它仍然起作用

import win32gui
from time import time, sleep
import json
import datetime
from dateutil import parser
# from activities_to_large import *
# from main import *

previous_window = ""

first_time = True
start_time = datetime.datetime.now()
load_json = False


class ActivityList:
    def __init__(self, activities, active_window):
        self.activities = activities
        self.active_window = active_window

    def data_from_json(self):
        added_to_existing = False

        data = {"activities": []}
        if load_json == True:
            with open("Screentime/activities.json", "r") as f:
                data = json.load(f)
            for i in range(len(data["activities"])):
                if data["activities"][i]["name"] == self.active_window:
                    # append only time becausse this window already exists in JSON file
                    data["activities"][i]["time_entry"].append(
                        self.specific_times()
                    )
                    added_to_existing = True

        elif load_json == False:
            # JSON wont load if empty and if that is the case then this line will activate
            data["activities"].append(self.process_json(data))
            added_to_existing = True

        if added_to_existing == False:
            # If this window is the first instance in Json file, it must create a new dict
            data["activities"].append(self.process_json(data))

        first_time = False
        with open("Screentime/activities.json", "w") as json_file:
            json.dump(data, json_file, indent=4, sort_keys=True)
        return data

    def process_json(self, data):
        current_window_data = {
            "name": self.active_window,
            "time_entry": [self.specific_times()],
        }
        return current_window_data

    def time_entries(self, start_time_dt, end_time_dt):
        self.start_time_dt = start_time
        self.end_time_dt = end_time_dt
        self.start_time = self.start_time_dt.strftime("%Y-%m-%d %H:%M:%S")
        self.end_time = self.end_time_dt.strftime("%Y-%m-%d %H:%M:%S")
        self.days = 0
        self.hours = 0
        self.minutes = 0
        self.seconds = 0

    # def current_time(self):
    #     # time = datetime.datetime.now()

    #     return_list = self.specific_times(start_time, end_time)
    #     return return_list

    def specific_times(self):
        total_time = self.end_time_dt - self.start_time_dt
        print(total_time)
        self.days, self.seconds = total_time.days, total_time.seconds
        print(self.days)
        self.hours = self.days * 24 + self.seconds // 3600
        print(self.hours)
        self.minutes = (self.seconds % 3600) // 60
        print(self.minutes)
        self.seconds = self.seconds % 60
        print(self.seconds)

        return_list = {
            "start_time": self.start_time,
            "end_time": self.end_time,
            "days": self.days,
            "hours": self.hours,
            "minutes": self.minutes,
            "seconds": self.seconds,
        }
        return return_list

相关问题 更多 >