Python,把Json-Data放在一个变量中



我想把Json-File数据放到单独的变量中。所以我可以用这些变量来做其他事情。我能够从其他QDialog的输入创建json文件。下一步是将输入从json文件中取出,并将其插入到各个变量中。所以json:Line1 into self。line1Config等。

self.jsonfile = str(self.tn+'.json')
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)
jsonFile = open(self.jsonfile, 'w')
jsonFile.write(jsonString)
jsonFile.close()

对于下面的代码,它不起作用:

def CheckIfJsonFileIsAlreadyThere(self):
try:
if os.path.isfile(self.jsonfile) == True:
data = json.loads(self.jsonfile)
for daten in data:
self.line1Config = daten['Line1']
self.line2Config = daten['Line2']
self.line3Config = daten['Line3']
else:
raise Exception

except Exception:
self.label_ShowUserText("There are no configuration yet. Please create some 
configuartions")
self.label_ShowUserText.setStyleSheet("color: black; font: 12pt "Arial";")

错误码:

Traceback (most recent call last):
File "c:path", line 90, in CheckIfJsonFileIsAlreadyThere
data = json.loads(self.jsonfile)
File "C:Program FilesWindowsAppsPythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0libjson__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:Program FilesWindowsAppsPythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0libjsondecoder.py", line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 11 (char 10)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:path", line 38, in <module>
MainWindow = mainwindow()
File "path", line 21, in __init__
self.d = Generator_Dialog(self)
File "c:path", line 55, in __init__
self.CheckIfJsonFileIsAlreadyThere()
File "c:path", line 100, in CheckIfJsonFileIsAlreadyThere
self.label_ShowUserText("There are no configuration yet. Please create some configuartions")
TypeError: 'QLabel' object is not callable 

你有两个问题:

  1. json。Loads需要一个字符串,而不是路径。改为:

    with open(self.jsonfile) as jsonfile:
    data = json.load(jsonfile)
    
  2. 您忘记了您的"配置"JSON结构中的级别:

    for daten in data["Config"]:
    self.line1Config = daten['Line1']
    self.line2Config = daten['Line2']
    self.line3Config = daten['Line3']
    

我为您创建了一个最小的工作示例:https://www.online-python.com/ZoGQWjlehI

由于JSON文档来自self.jsonfile = str(self.tn+'.json')的特定文件,因此使用json.load()代替json.loads():

  • json.loads

    反序列化s (一个str、bytes或bytearray实例包含JSON文档)到Python对象

  • json.load

    反序列化支持.read()文本文件或二进制文件包含JSON文档)到Python对象

修改这一行:

data = json.loads(self.jsonfile)

with open(self.jsonfile) as opened_file:
data = json.load(opened_file)

最新更新