我正在尝试使用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
关于, 罗希斯
答案 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
}