我正在尝试使用Ruby解析复杂的JSON对象:
"data": [{
"resourceId": 381,
"resourceName": "Admin.Config",
"resourceDesc": "Correspondence Admin -> Configuration",
"permissions": [{
"id": 1081,
"operation": "Update",
"assignedToRoleFlag": false
}, {
"id": 1071,
"operation": "Read",
"assignedToRoleFlag": false
}],
"productName": "Doc"
}, {
"resourceId": 391,
"resourceName": "Admin.Usage",
"resourceDesc": "Correspondence Admin -> Usage",
"permissions": [{
"id": 1091,
"operation": "Read",
"assignedToRoleFlag": false
}],
"productName": "Doc"
}, ...................................... }
问题是,我想解析一下,以['data']['permissions']['id']
为例['data']['resourceName'] = Admin.Config
和['data']['permissions']['operation'] = Read
。
我正在尝试获取此值(perm =上面的JSON响应):
#!/usr/bin/env ruby
require 'json'
perm = response.body
file = perm
data_hash = JSON.parse(file)
data_you_want = data_hash["data"].detect do |h|
h["resourceName"] == "Admin.Config" and h["permissions"][0]["operation"] == "Read"
end
permid = data_you_want['permissions'][0]['id']
puts permid
答案 0 :(得分:2)
更简单的解决方案:
guidz=[]
file = perm
data_hash = JSON.parse(file)
data_you_want = data_hash["data"].detect do |h|
puts h['permissions']
if h["resourceName"] == "Admin.Config"
h["permissions"].each do |permisiune|
guidz << permisiune['id'] if permisiune['operation'] == 'Read'
guidz << permisiune['id'] if permisiune['operation'] == 'Update'
end
end
if h["resourceName"] == "Admin.Usage"
h["permissions"].each do |permisiune|
guidz << permisiune['id'] if permisiune['operation'] == 'Read'
end
end
end
puts guidz.inspect