Python读取JSON文件赋值变量报JSONDecodeError与QLabel调用错误如何解决
错误原因与修复方案
错误1:JSONDecodeError: Extra data
产生原因:
json.loads()方法用于解析JSON格式的字符串,你传入的是文件路径字符串,而非JSON内容,因此解析失败。读取JSON文件需要先打开文件对象,使用不带s的json.load()方法读取。- 你写入的JSON结构外层是字典,所有配置存储在
configs对应的列表中,读取后直接遍历data只会遍历字典的键(也就是字符串configs),无法取到Line1等字段。
错误2:TypeError: 'QLabel' object is not callable
产生原因:self.label_ShowUserText是QLabel控件的实例,不是可调用的函数,不能直接加括号传参修改显示内容,需要调用QLabel内置的setText()方法设置文本。
修复后的代码
import json import os # (你的其他代码保持不变,仅修改CheckIfJsonFileIsAlreadyThere方法) def CheckIfJsonFileIsAlreadyThere(self): try: if os.path.isfile(self.jsonfile): # 用with open自动管理文件关闭,更安全 with open(self.jsonfile, 'r', encoding='utf-8') as f: data = json.load(f) # 遍历configs下的配置列表 for daten in data['configs']: self.line1Config = daten['Line1'] self.line2Config = daten['Line2'] self.line3Config = daten['Line3'] else: raise Exception except Exception: # 调用setText方法设置标签文本 self.label_ShowUserText.setText("There are no configuration yet. Please create some configurations") self.label_ShowUserText.setStyleSheet("color: black; font: 12pt \"Arial\";")
可选优化(非必须)
写入JSON的代码也可以用with open优化,避免异常时文件未正常关闭:
def WriteJSON(self): self.NewConfigJSON = {} self.NewConfigJSON['configs'] = [] self.NewConfigJSON['configs'].append({ 'Line1': str(self.CreatNewJsonW.Line1), 'Line2': str(self.CreatNewJsonW.Line2), 'Line3': str(self.CreatNewJsonW.Line3) }) jsonString = json.dumps(self.NewConfigJSON, indent=4, ensure_ascii=False) with open(self.jsonfile, 'w', encoding='utf-8') as jsonFile: jsonFile.write(jsonString)
内容的提问来源于stack exchange,提问作者wimsen
相关产品推荐
相关产品推荐

