Json
將 json 輸出列印到單行,以逗號分隔
我是 JQ 的新手,我有以下 json 文件
[ { "userId" : "jens", "firstName" : "jens", "lastName" : "jens", "emailAddress" : "admin@example.org", "source" : "default", "status" : "active", "readOnly" : false, "roles" : [ "reader" ], "externalRoles" : [ ] }, { "userId" : "admin", "firstName" : "Administrator", "lastName" : "User", "emailAddress" : "admin@example.org", "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", ]
請指導我如何獲得上述輸出。
如果你這樣做
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"]