0

i have a python function that read from json file and must write these data into a table widgets.

JSON file contains: (dictionary that handle a list where the item list are dictionary)

  • dictionary
  • list
  • dictionary

i tried to make a loop and read from the json file but i did not succeed.

json file

 "default":"dbLocal",
            "DB":[
                {
                 "name":"dbLocal",
                 "source":"dbtest",
                 "type":"sqlite3",
                 "comment":"Initially created DB"
                }
            ]
        }

function.py

def writeIntoTable(self):
    with open(os.path.join(self.homeDir,self.subDir,self.refFile)) as refJsonHandler:
        jsonData = json.load(refJsonHandler)
        #print(jsonData)
        for distro in jsonData:
            print(distro[''])<== here i tried to put the key of dictionary like "name"            

the system display this error :

File "app.py", line 79, in writeIntoTable print(distro['source']) TypeError: string indices must be integers

Pyt Leb
  • 99
  • 2
  • 10
  • 1
    First, that's not a valid JSON file; it's a fragment of an object. Second, you can easily print the value of `distro` to see that it isn't a `dict`. You might want `jsonData[distro]` instead, if `jsonData` really is a `dict`. – chepner Mar 15 '18 at 20:32
  • Show us more of the JSON file, preferably the whole thing if it's not too big. For now, I'm guessing you want `for distro in jsonData['DB']: print(distro['name'])` – Alex Hall Mar 15 '18 at 20:36
  • @chepner but in your answer i will not be able to select a value from the "DB" like name or source right ? – Pyt Leb Mar 15 '18 at 20:38
  • 1
    As Alex Hall mentions, you are looking at the wrong dict. `jsonData` doesn't have `name` or `source` as a key, but `jsonData['DB'][0]`, `jsonData['DB'][1]`, etc., would appear to. – chepner Mar 15 '18 at 20:43
  • @AlexHall this json file is manually created and it contains for now just this dictionary and list – Pyt Leb Mar 15 '18 at 20:45

1 Answers1

0

When iterating a dictionary, you are iterating through the keys.

for distro in jsonData:
    print(distro['']) # "distro" is the key "default"

To get the value from the key:

for distro in jsonData:
    print(jsonData[distro]) # This is the value of dict "jsonData" at key "distro"
Brad Fallon
  • 169
  • 1
  • 7
  • so after i read and get all the json data how to display it in a table widget? – Pyt Leb Mar 15 '18 at 20:43
  • so after i read and get all the json data how to display it in a table widget? – Pyt Leb Mar 15 '18 at 20:43
  • What's a table widget? That's an *entirely* different question. – chepner Mar 15 '18 at 20:44
  • Not sure what you mean by "table widget". You can print the data with print(json.dumps(jsonData, indent=4, sort_keys=True)) https://stackoverflow.com/questions/12943819/how-to-prettyprint-a-json-file – Brad Fallon Mar 15 '18 at 20:48