json 如何修复TypeError不知道什么是错的

tv6aics1  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(174)

我得到这个错误:

File "C:\file\path\to\json-parsing.py", line 33, in parse_output_file
    session['duration'] = session['end_time'] - session['start_time'] if session['end_time'] is not None else None
                          ~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'

我不知道如何解决这个问题。有人能解释一下吗
我的代码如下:

import json     #import json and datetime libraries
from datetime import datetime

def parse_output_file(file_path):   #function to load json file
    with open(file_path, 'r') as file:
        data = json.load(file)
    
    sessions = {}   #initialize empty dictionary
    
    for record in data:     #parse through array for each record
        session_id = record['id']
        session_type = record['type']
        timestamp = int(record['timestamp'])
        comments = record.get('comments', '')
        
        if session_id not in sessions: #creates new session_id if session_id is not found
            sessions[session_id] = {'id': session_id, 'start_time': None, 'end_time': None, 'duration': None, 'late_return': False, 'damaged': False, 'comments': ''}
        
        if session_type == 'START':     #checks session type and sets start time and end time
            sessions[session_id]['start_time'] = timestamp
        elif session_type == 'END':
            sessions[session_id]['end_time'] = timestamp
            if sessions[session_id]['end_time'] is not None:
                sessions[session_id]['damaged'] = bool(comments) #sets damaged and comments keys in the dictionary if present
                sessions[session_id]['comments'] = comments
    
    for session in sessions.values():
        start_time = datetime.fromtimestamp(session['start_time']).strftime('%Y-%m-%d %H:%M:%S') if session['start_time'] is not None else None
        if session['end_time'] is not None:
            end_time = datetime.fromtimestamp(session['end_time']).strftime('%Y-%m-%d %H:%M:%S')
        else:
            end_time = None
        session['duration'] = session['end_time'] - session['start_time'] if session['end_time'] is not None else None
        late_return = session['duration'] > 24 * 3600 if session['duration'] is not None else False      #checks is the session is late by comparing to 24 hours
        
        
        session['late_return'] = late_return
        
        print(f"Session ID: {session['id']}")   #iterate through sessions dictionary and prints data
        print(f"Start Time: {start_time}")
        print(f"End Time: {end_time}")
        print(f"Duration: {session['duration']} seconds")
        print(f"Late Return: {late_return}")
        print(f"Damaged: {session['damaged']}")
        print(f"Comments: {session['comments']}")
        print()
    
    # Store summary records to a file
        
# Replace 'path/to/your/file.json' with the actual path to your JSON file
file_path = r'output.json'

# Usage
parse_output_file(file_path)`

我试图运行这个python脚本来解析JSON文件并获得输出摘要。

fkvaft9z

fkvaft9z1#

尝试:

start = session['start_time']
end = session['end_time']

if end is None or start is None:
    session['duration'] = None
else:
    session['duration'] = end - start

相关问题