【问题标题】:how to select values from json file using python如何使用python从json文件中选择值
【发布时间】:2018-03-15 20:30:36
【问题描述】:

我有一个从 json 文件读取的 python 函数,并且必须将这些数据写入表小部件。

JSON 文件包含:(处理项目列表为字典的列表的字典)

  • 字典
  • 列表
  • 字典

我试图创建一个循环并从 json 文件中读取,但我没有成功。

json 文件

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

函数.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"            

系统显示此错误:

文件“app.py”,第 79 行,在 writeIntoTable 中 print(distro['source']) TypeError: 字符串索引必须是整数

【问题讨论】:

  • 首先,这不是一个有效的 JSON 文件;它是一个对象的片段。其次,您可以轻松打印distro 的值以查看它不是dict。如果jsonData 真的是dict,您可能需要jsonData[distro]
  • 向我们展示更多的 JSON 文件,如果不是太大的话,最好是完整的。现在,我猜你想要for distro in jsonData['DB']: print(distro['name'])
  • @chepner 但在您的回答中,我将无法从“数据库”中选择一个值,例如名称或来源?
  • 正如 Alex Hall 所提到的,您正在查看错误的字典。 jsonData 没有 namesource 作为键,但 jsonData['DB'][0]jsonData['DB'][1] 等会出现。
  • @AlexHall 这个 json 文件是手动创建的,它现在只包含这个字典和列表

标签: python json list dictionary


【解决方案1】:

当迭代字典时,你正在迭代键。

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

从键中获取值:

for distro in jsonData:
    print(jsonData[distro]) # This is the value of dict "jsonData" at key "distro"

【讨论】:

  • 所以在我读取并获取所有 json 数据后如何在表格小部件中显示它?
  • 所以在我读取并获取所有 json 数据后如何在表格小部件中显示它?
  • 什么是表格小部件?这是一个完全不同的问题。
  • 不确定您所说的“表格小部件”是什么意思。您可以使用 print(json.dumps(jsonData, indent=4, sort_keys=True)) stackoverflow.com/questions/12943819/… 打印数据
猜你喜欢
  • 2016-10-10
  • 2020-03-13
  • 1970-01-01
  • 1970-01-01
  • 2019-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多