Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
547 views
in Technique[技术] by (71.8m points)

json - jq - add preffix to values on array

input json:

[
{
  "login": "u1",
  "name": "u1",
  "role": "User",
  "groups": [
    {
      "id": "1234",
      "name": "G1"
    },
    {
      "id": "1235",
      "name": "G2"
    }
  ],
  "created": "2020-05-11 11:06"
},
{
  "login": "u2",
  "name": "u2",
  "role": "User",
  "groups": null,
  "created": "2020-05-11 11:06"
}
]

I use following filter to get users and groups they are member of:

$ jq -r '
  .[]
  | [.login,
     .name,
     ( if .groups == null 
       then "grp:-" 
       else (del(.groups[]
             | select(.name=="All Users"))
            | [.groups[].name] | join("|")) 
       end )]
  | @tsv' json
u1      u1      G1|G2
u2      u2      grp:-

How to add grp: prefix for each found group? Expected output would be:

u1      u1      grp:G1|grp:G2
u2      u2      grp:-
question from:https://stackoverflow.com/questions/65833864/jq-add-preffix-to-values-on-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use + to concatenate strings:

jq -r '.[]
       | [.login,.name,(
           if .groups == null
           then "grp:-"
           else (
               del(.groups[] | select(.name=="All Users"))
               | ["grp:" + .groups[].name]
#                 ~~~~~~~~
               | join("|")
           )
           end
      )]
      | @tsv' 

You can even avoid specifying "grp:" twice, but you need to return an array from the then branch, too:

jq -r '.[]
       | [.login, .name, (
           (
               if .groups == null
               then ["-"]
               else (
                   del(.groups[] | select(.name=="All Users"))
                   | [.groups[].name]
               )
               end
           )
           | map("grp:" + .)
           | join("|")
       )]
       | @tsv'

Update: Getting inspiration from peak I guess this produces the output you wanted:

jq -r '.[]
        | .groups //= []
        | del(.groups[] | select(.name=="All Users"))
        | .groups[0] //= {name: "-"}
        | [.login, .name, ( ["grp:" + (.groups[].name)] | join("|") ) ]
        | @tsv'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...