我试图写一个代码来跟踪屏幕时间的使用情况。我在尝试向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
如果有人能用简单的英语解释发生了什么以及如何解决这个问题,请回答
我只是把所有的东西都添加到了主类中。我认为班级之间的转换一定是个问题。虽然我仍然不明白为什么以前的代码不起作用,尽管这段代码更脏,也没有那么有条理,但它仍然起作用
相关问题 更多 >
编程相关推荐