简体   繁体   中英

how to select values from json file using python

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM