Iokanaan Iokan
Iokanaan Iokan

Reputation: 775

writing array values to the same line while extracting data from json using jq

I have the following json:

{
  "jsonrpc": "2.0",
  "result": [
    {
      "hostid": "15226",
      "host": "host1",
      "groups": [
        {
          "groupid": "56",
          "name": "Group 1",
          "internal": "0",
          "flags": "0"
        },
        {
          "groupid": "112",
          "name": "Group 2",
          "internal": "0",
          "flags": "0"
        }
      ]
    }
  ],
  "id": 1
}

I am trying to extract values from it to create this line using jq:

15226, host1, Group 1, Group 2

I am able to do the following but it's not quite what I want:

jq -r '.result[] | .hostid + ", " + .host + ", " + .groups[].name' hostlist.json
15226, host1, Group 1
15226, host1, Group 2

Couldn't figure it out, any help is appreciated.

Upvotes: 3

Views: 3885

Answers (3)

jq170727
jq170727

Reputation: 14655

join / @csv as described by hek2mgl is definitely the easiest way to do this.

For reference, here is a version that uses string interpolation to build the initial part of the line and reduce to add the group names to it:

  .result[]
| reduce .groups[].name as $g (
      "\(.hostid), \(.host)"
    ; . + ", " + $g 
  )

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 157990

You can use this:

jq -r '.result[]|[.hostid,.host,.groups[].name]|@csv'

Output:

"15226","host1","Group 1","Group 2"

@csv makes proper csv out of it. If you don't like that, a simple join(',') should be enough:

jq -r '.result[]|[.hostid,.host,.groups[].name]|join(",")'

Output:

15226,host1,Group 1,Group 2

Upvotes: 3

bstockwell
bstockwell

Reputation: 514

Using reduce seems to do the trick: .result[] | .hostid + ", " + .host + ", " + (reduce .groups[].name as $gn (""; . + $gn + " "))

You might want to trim the output as well, as this produces and extra whitespace character.

Upvotes: 2

Related Questions