0

I want to put Json-File data in to individual variables. So I can use the variables for otherthings. Im able to create a Json-file from inputs from a other QDialog. The next move is to get the inputs back out of the Json-File and insert it into individual variables. So json:Line1 into self.line1Config and so on.

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()

With the code below, it wont work:

  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\";")

The Error Code:

Traceback (most recent call last):
  File "c:\path", line 90, in CheckIfJsonFileIsAlreadyThere
    data = json.loads(self.jsonfile)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\json\decoder.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 
4
  • 1
    What are the contents of the JSON file? Commented Aug 31, 2021 at 12:05
  • {"Configs": [{"Line1": "some text", "Line2": "some text", "Line3": "some text"}]} @ScottHunter Commented Aug 31, 2021 at 12:10
  • you are using json.loads(), which expects the serialized JSON data as a parameter, but you are passing there self.jsonfile, which is the name of the JSON file, that won't work. You have to pass there content of the file. Commented Aug 31, 2021 at 12:20
  • Sorry, Im new programer. I didn't understand what you mean. Or what I should do. @yedpodtrzitko Commented Aug 31, 2021 at 12:27

2 Answers 2

1

You have here two problems:

  1. json.loads needs a string and not a path. Change it to:

    with open(self.jsonfile) as jsonfile:
         data = json.load(jsonfile)
    
  2. You have forgotten your "Config" Level in your JSON structure:

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

I created a minimal working example for you: https://www.online-python.com/ZoGQWjlehI

Sign up to request clarification or add additional context in comments.

Comments

1

Since the JSON document comes from a file specifically from self.jsonfile = str(self.tn+'.json'), then use json.load() instead of json.loads():

  • json.loads

    Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object

  • json.load

    Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object

Change this line:

data = json.loads(self.jsonfile)

To

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

3 Comments

I did. Traceback (most recent call last): File "c:\path", line 94, in CheckIfJsonFileIsAlreadyThere self.line1Config = daten['Line1'] TypeError: string indices must be integers What is here the Problem?
That means you are now already reading the contents of the file :) Can you share the contents of your .json file?
{"Configs": [{"Line1": "some text", "Line2": "some text", "Line3": "some text"}]}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.