使用python根据选择条件从json提取值

时间:2018-06-29 10:25:54

标签: python json python-3.x dictionary

我正在尝试使用python根据选择条件从json提取值。 我的Json文件如下所示:

{
  "bindings": [
    {
      "members": [
        "user:rohithmn3@gmail.com"
      ],
      "role": "roles/browser"
    },
    {
      "members": [
        "serviceAccount:admin-user@linuxacademy-3.iam.gserviceaccount.com",
        "user:rohithmn03@gmail.com"
      ],
      "role": "roles/owner"
    },
    {
      "members": [
        "user:rohithmn3@gmail.com"
      ],
      "role": "roles/viewer"
    }
  ],
  "etag": "BwrRsH-UhJ0=",
  "version": 1
}

我正在尝试基于user在python中解析以上文件。例如:获取为用户rohithmn3@gmail.com定义的角色;根据json的输出应为:

roles/browser
roles/viewer

关于, 罗希斯

1 个答案:

答案 0 :(得分:1)

使用列表理解和字典输入d

var = 'rohithmn3@gmail.com'
res = [subd['role'] for subd in d['bindings'] if 'user:'+var in subd['members']]

print(res)

['roles/browser', 'roles/viewer']

设置

d = {
  "bindings": [
    {
      "members": [
        "user:rohithmn3@gmail.com"
      ],
      "role": "roles/browser"
    },
    {
      "members": [
        "serviceAccount:admin-user@linuxacademy-3.iam.gserviceaccount.com",
        "user:rohithmn03@gmail.com"
      ],
      "role": "roles/owner"
    },
    {
      "members": [
        "user:rohithmn3@gmail.com"
      ],
      "role": "roles/viewer"
    }
  ],
  "etag": "BwrRsH-UhJ0=",
  "version": 1
}