如何使用python从json文件中选择值

时间:2018-03-15 20:30:36

标签: python json list dictionary

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

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

  • 字典
  • 列表
  • 字典

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

json文件

 "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"            

系统显示此错误:

  

文件&#34; app.py&#34;,第79行,在writeIntoTable中       print(发行版[&#39; source&#39;])TypeError:字符串索引必须是整数

1 个答案:

答案 0 :(得分:0)

在迭代字典时,您正在遍历键。

// Send an Intent with an action named "open-next-dialog". The Intent sent should be received by your Activity
private void openNextDialogIfAny() {
  if(messageStack.isEmpty()) return; // No more dialogs to be shown.

  Intent intent = new Intent("open-next-dialog");
  intent.putExtra("message", messageStack.pop());
  intent.putExtra("layout_id", layoutStack.pop());
  LocalBroadcastManager.getInstance(YourActivity.this).sendBroadcast(intent);
}

从密钥中获取值:

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