输入json文件:
[
{
"id": "1e9b2215-9efd-67cc-9113-1e21c74f09d3",
"login": "u0159",
"name": "Pat ABC",
"role": "User",
"groups": null,
"disabled": false,
"lLoginTime": 1567158950468,
"lLoginFrom": "192.168.100.11"
},
{
"id": "1e9b2215-9efd-67cc-9113-2b21c74f09d3",
"login": "u0154",
"name": "Roman ABC",
"role": "User",
"groups": [
{
"id": "1e8dc82a-596f-623c-8bc5-100000000000",
"name": "Default ABC"
},
{
"id": "1e99833f-9876-65d0-9d24-237228b9d9e0",
"name": "AGE"
}
],
"disabled": false,
"lLoginTime": 1567158950468,
"lLoginFrom": "192.168.100.11"
},
{
"id": "1e9b2215-9c2b-64f4-a0f1-47abdab7ae5f",
"login": "u0155",
"name": "Tomas CDE",
"role": "User",
"groups": [
{
"id": "1e8dc82a-596f-623c-8bc5-100000000000",
"name": "ZZZ"
},
{
"id": "1e8dc82a-596f-623c-8bc5-100000000000",
"name": "Default ABC"
},
{
"id": "1e99234f-9876-65d0-9d24-534528b9d9e0",
"name": "NTE"
}
],
"disabled": false,
"lLoginTime": 1566302653093,
"lLoginFrom": "192.168.100.16"
}
]
我想扩展以下过滤器:
$ jq -r '.[]|[.id, .login, ( if .groups == null then "n/a" else ([.groups[].name]|join("|")) end )]|@tsv' /tmp/test__
1e9b2215-9efd-67cc-9113-1e21c74f09d3 u0159 n/a
1e9b2215-9efd-67cc-9113-2b21c74f09d3 u0154 Default ABC|AGE
1e9b2215-9c2b-64f4-a0f1-47abdab7ae5f u0155 ZZZ|Default ABC|NTE
从由 | 分隔的组列表中删除所有“默认 ABC” 输出时
我尝试了额外的 if 但失败并出现错误:
$ jq -r '.[]|[.id, .login, ( if .groups == null then "n/a" else ( if .groups[].name != "Default ABC" then [.groups[].name]|join("|")) end ) end )]|@tsv' /tmp/test__
jq: error: syntax error, unexpected ')' (Unix shell quoting issues?) at <top-level>, line 1:
感谢任何提示...
示例 json 的预期输出为:
1e9b2215-9efd-67cc-9113-1e21c74f09d3 u0159 n/a
1e9b2215-9efd-67cc-9113-2b21c74f09d3 u0154 AGE
1e9b2215-9c2b-64f4-a0f1-47abdab7ae5f u0155 ZZZ|NTE
更新: oliv 提供的解决方案:
$ jq -r '.[]|[.id,.login,if .groups then (.groups|map(select(.name != "Default ABC").name)|join("|")) else "n/a" end]|@tsv' /tmp/test__
1e9b2215-9efd-67cc-9113-1e21c74f09d3 u0159 n/a
1e9b2215-9efd-67cc-9113-2b21c74f09d3 u0154 AGE
1e9b2215-9c2b-64f4-a0f1-47abdab7ae5f u0155 ZZZ|NTE
假设如果
groups
存在,它是一个数组,你可以过滤掉不需要的name
使用select
: