我是 JQ 新手,我有以下 json 文件
[
{
"userId" : "jens",
"firstName" : "jens",
"lastName" : "jens",
"emailAddress" : "[email protected]",
"source" : "default",
"status" : "active",
"readOnly" : false,
"roles" : [ "reader" ],
"externalRoles" : [ ]
}, {
"userId" : "admin",
"firstName" : "Administrator",
"lastName" : "User",
"emailAddress" : "[email protected]",
"source" : "default",
"status" : "changepassword",
"readOnly" : false,
"roles" : [ "app-admin" ],
"externalRoles" : [ ]
}]
现在我想打印如下格式
"userId" : "jens","roles" : [ "reader" ]
"userId" : "admin", "roles" : [ "app-admin" ],
我怎样才能实现这个目标?我尝试使用这个命令
jq -r '.[].userId,.[].roles'
但它分散了数据,如下所示
jens
admin
[]
[
"reader",
"app-admins",
]
请指导我如何才能得到上述输出。
答案1
如果你这样做
jq -c '.[] | {userid: .userId, roles: .roles}'
你会得到
{"userid":"jens","roles":["reader"]}
{"userid":"admin","roles":["app-admin"]}
该-c
标志会将每个对象放在自己的行上,因此只要您没有嵌套对象,这应该可以满足您的要求。后期处理例如去掉大括号:
jq -c '.[] | {userid: .userId, roles: .roles}' | sed -e 's/^{//g' -e 's/}$//g'
产生
"userid":"jens","roles":["reader"]
"userid":"admin","roles":["app-admin"]